Certain System.Threading.Tasks.Task
constructors take a CancellationToken
as a parameter:
CancellationTokenSource source = new CancellationTokenSource();
Task t = new Task (/* method */, source.Token);
What baffles me about this is that there is no way from inside the method body to actually get at the token passed in (e.g., nothing like Task.CurrentTask.CancellationToken
). The token has to be provided through some other mechanism, such as the state object or captured in a lambda.
So what purpose does providing the cancellation token in the constructor serve?
Cancellation is not a simple a case as many might think. Some of the subtleties are explained in this blog post on msdn:
For example:
http://blogs.msdn.com/b/pfxteam/archive/2009/06/22/9791840.aspx
The constructor uses the token for cancellation handling internally. If your code would like access to the token you are responsible for passing it to yourself. I would highly recommend reading the Parallel Programming with Microsoft .NET book at CodePlex.
Example usage of CTS from the book:
Passing this token into the Task constructor associates it with this task.
Quoting Stephen Toub's answer from MSDN: