Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# cancel a long running task that not a loop

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?

like image 393
prime23 Avatar asked Feb 22 '12 07:02

prime23


1 Answers

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.

like image 149
Jon Skeet Avatar answered Sep 29 '22 23:09

Jon Skeet