本文介绍了我该如何中止/取消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方法还取消线程不推荐。你可以看看的following博客文章这也解释了取消使用取消标记任务的正确方法。这里有一个例子:
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任务?
发布评论