C# cancel a long running task that not a loop

↘锁芯ラ 提交于 2020-01-03 18:59:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!