Why does TaskFactory.StartNew receive a Cancellati

2019-07-07 08:13发布

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条回答
贪生不怕死
2楼-- · 2019-07-07 08:13

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.

查看更多
登录 后发表回答