How do I abort/cancel TPL Tasks?

前端 未结 12 2286
佛祖请我去吃肉
佛祖请我去吃肉 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:46

    You should not try to do this directly. Design your tasks to work with a CancellationToken, and cancel them this way.

    In addition, I would recommend changing your main thread to function via a CancellationToken as well. Calling Thread.Abort() is a bad idea - it can lead to various problems that are very difficult to diagnose. Instead, that thread can use the same Cancellation that your tasks use - and the same CancellationTokenSource can be used to trigger the cancellation of all of your tasks and your main thread.

    This will lead to a far simpler, and safer, design.

提交回复
热议问题