我该如何中止/取消TPL任务? [英] How do I abort/cancel TPL Tasks?

查看:138
本文介绍了我该如何中止/取消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方法还取消线程不推荐。你可以看看的<一个href="http://blogs.msdn.com/b/csharpfaq/archive/2010/07/19/parallel-programming-task-cancellation.aspx">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任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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