问题
I am new to c# task, what I want to do is convert
downloadThread = new Thread(DownLoadFile); downloadThread.Start();
to task like
var t = Task.Factory.StartNew(DownLoadFile);
I also knew use CancellationTokenSource to cancel. But examples I saw are all long loop running thread, like for, foreach, while, and check IsCancellationRequested to cancel a task in loop.
if (ct.IsCancellationRequested) { break; }
but my long running task is to download a file from ftp, GetFile is from third party dll.
ftp.GetFile(ftpPath, dest, false);
is my long running task, no loops, how to check an cancel it?
回答1:
If the third party API doesn't support cancellation, there's no clean way of doing it. You can abort the thread, but I'd strongly advise that you only do that if you're killing the whole process (or at least the AppDomain).
If at all possible, find an equivalent API which does support cancellation, or just abandon the request and let it take its course, just ignoring the result.
来源:https://stackoverflow.com/questions/9390599/c-sharp-cancel-a-long-running-task-that-not-a-loop