问题
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