NET问答: 如何取消或中止 Task 执行 ?

咨询区

  • Patrice Pezillier

我在一个线程里创建了若干了task并开启执行,当我在业务逻辑中执行了 Thread.Abort() 之后,我发现这些 Task 并没有被终止掉?

问题来了,我如何将 Abort() 传递到内部的 Task 呢?

回答区

  • Darin Dimitrov

你做不到的,Task默认就依托于底层线程池中的线程,同时用 Thread.Abort() 来中止线程也是不推荐的,在 Task 中推荐的做法是使用 cancellation tokens,可参考如下代码:


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

  • Florian Rappl

之所以在中止Thread后Task没有被终止的原因在于:你在Task中没有捕获到当前的 Thread ,如果做到了这点,那就可以完美解决了,参考如下代码:


void Main()
{
    Thread thread = null;

    Task t = Task.Run(() => 
    {
        //Capture the thread
        thread = Thread.CurrentThread;

        //Simulate work (usually from 3rd party code)
        Thread.Sleep(1000);

        //If you comment out thread.Abort(), then this will be displayed
        Console.WriteLine("Task finished!");
    });

    //This is needed in the example to avoid thread being still NULL
    Thread.Sleep(10);

    //Cancel the task by aborting the thread
    thread.Abort();
}

点评区

其实这是大家用多线程开发必然会遇到的一个问题,对 CancellationToken 的理解和运用还是非常重要的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值