How do I abort/cancel TPL Tasks?

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

    You can use a CancellationToken to control whether the task gets cancelled. Are you talking about aborting it before it's started ("nevermind, I already did this"), or actually interrupting it in middle? If the former, the CancellationToken can be helpful; if the latter, you will probably need to implement your own "bail out" mechanism and check at appropriate points in the task execution whether you should fail fast (you can still use the CancellationToken to help you, but it's a little more manual).

    MSDN has an article about cancelling Tasks: http://msdn.microsoft.com/en-us/library/dd997396.aspx

提交回复
热议问题