C#取消长时间运行的任务而不是循环 [英] C# cancel a long running task that not a loop

查看:289
本文介绍了C#取消长时间运行的任务而不是循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是c#任务的新手,我想做的就是转换

I am new to c# task, what I want to do is convert

downloadThread = new Thread(DownLoadFile); 
downloadThread.Start();

完成任务

var t = Task.Factory.StartNew(DownLoadFile);

我也知道使用CancellationTokenSource来取消任务.但是,我看到的示例都是长时间运行的线程,例如forforeachwhile,它们检查IsCancellationRequested来取消循环中的任务.

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;
}

但是我长期运行的任务是使用FTP下载文件. GetFile方法来自第三方dll库.

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?

推荐答案

如果第三方API不支持取消,则没有干净的方法.您可以 中止线程,但是我强烈建议您仅在杀死整个过程(或至少杀死AppDomain)的情况下这样做.

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).

如果可能的话,找到一个等效的API,它支持取消,或者放弃请求并顺其自然,而忽略结果.

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.

这篇关于C#取消长时间运行的任务而不是循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆