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 know to use CancellationTokenSource to cancel the task. However, the examples I saw are all long loop running threads, such as for
, foreach
, while
, and they check IsCancellationRequested
to cancel the task in the loop.
if (ct.IsCancellationRequested)
{
break;
}
But my long running task is to download a file with FTP. The GetFile
method is from a third party dll library.
ftp.GetFile(ftpPath, dest, false);
Since my long running task is not in any loops, how can I check for and then cancel it?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With