如何中止/取消 TPL 任务? [英] How do I abort/cancel TPL Tasks?
本文介绍了如何中止/取消 TPL 任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在一个线程中,我创建了一些 System.Threading.Task
并启动每个任务.
In a thread, I create some System.Threading.Task
and start each task.
当我执行 .Abort()
来终止线程时,任务不会中止.
When I do a .Abort()
to kill the thread, the tasks are not aborted.
如何将 .Abort()
传输到我的任务?
How can I transmit the .Abort()
to my tasks ?
推荐答案
你不能.任务使用线程池中的后台线程.也不推荐使用 Abort 方法取消线程.你可以看看 以下博客文章解释了使用取消令牌取消任务的正确方法.举个例子:
You can't. Tasks use background threads from the thread pool. Also canceling threads using the Abort method is not recommended. You may take a look at the following blog post which explains a proper way of canceling tasks using cancellation tokens. Here's an example:
class Program
{
static void Main()
{
var ts = new CancellationTokenSource();
CancellationToken ct = ts.Token;
Task.Factory.StartNew(() =>
{
while (true)
{
// do some heavy work here
Thread.Sleep(100);
if (ct.IsCancellationRequested)
{
// another thread decided to cancel
Console.WriteLine("task canceled");
break;
}
}
}, ct);
// Simulate waiting 3s for the task to complete
Thread.Sleep(3000);
// Can't wait anymore => cancel this task
ts.Cancel();
Console.ReadLine();
}
}
这篇关于如何中止/取消 TPL 任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文