Guys, I used to use a method like Task.Factory.StartNew(new Action(()=>{}), cancellationToken);
I have a question about the second argument cancellationToken. Because cancellationToken is a variable in my method, in the lambda expression, I can cancel my task using the field just like the msdn does; I’m not sure it’s recommend. In this case, is the second argument necessary here? It is passed in the StartNew method, but not actually used. Is there a scenario we need use this argument?
You need this argument if you want to cancel the Task. If you’re application doesn’t support or require cancellation then you could just say
Note that cancellation is cooperative so your code must poll for cancellation and respond accordingly.
For example:
You have to pass the cancellation token to the method otherwise it’s not attached to the task. The code within method is only using the token to respond to cancelation, either throwing or using the IsCancellationRequested to shut down. Although a task could cancel itself from within the lambda I guess. The task itself needs the token too.
here’s some further clarification:
From http://social.msdn.microsoft.com/Forums/en/parallelextensions/thread/c2f614f6-c96c-4821-84cc-050b21aaee45
See general discussion of cancellation here:
http://msdn.microsoft.com/en-us/library/ff963549.aspx for further discussion.