How do I abort/cancel TPL Tasks?

前端 未结 12 2294
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 11:42

In a thread, I create some System.Threading.Task and start each task.

When I do a .Abort() to kill the thread, the tasks are not aborted.

12条回答
  •  一个人的身影
    2020-11-22 11:47

    Like this post suggests, this can be done in the following way:

    int Foo(CancellationToken token)
    {
        Thread t = Thread.CurrentThread;
        using (token.Register(t.Abort))
        {
            // compute-bound work here
        }
    }
    

    Although it works, it's not recommended to use such approach. If you can control the code that executes in task, you'd better go with proper handling of cancellation.

提交回复
热议问题