Why does TaskFactory.StartNew receive a CancellationToken [duplicate]

怎甘沉沦 提交于 2019-12-23 13:08:20

问题


Possible Duplicate:
Cancellation token in Task constructor: why?

This method receives a CancellationToken:

CancellationTokenSource cts = new CancellationTokenSource(4);
var t = Task.Factory.StartNew(() => { // code }, cts.Token);

Since cancellation is cooperative (the actual working code needs to observe the cancellation token), What is the purpose of passing this to the StartNew method as an argument?


回答1:


It allows the task itself to be marked as cancelled which could allow any tasks that are waiting on the first task to be fired (ie any tasks queued up with the task.ContinueWith() method). Of course those subsequent tasks would most likely need to be cancelled too if the primary task is cancelled.

And you're absolutely right that the actual code being executed needs to be obeying the cancel token too.



来源:https://stackoverflow.com/questions/10863693/why-does-taskfactory-startnew-receive-a-cancellationtoken

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!