Cancellation token in Task constructor: why?
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:
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Task myTask = Task.Factory.StartNew(() =>
{
for (...)
{
token.ThrowIfCancellationRequested();
// Body of for loop.
}
}, token);
// ... elsewhere ...
cts.Cancel();
Passing a CancellationToken
into the Task
constructor associates it with the task.
Quoting Stephen Toub's answer from MSDN:
This has two primary benefits:
- If the token has cancellation requested prior to the
Task
starting to execute, theTask
won't execute. Rather than transitioning toRunning
, it'll immediately transition toCanceled
. This avoids the costs of running the task if it would just be canceled while running anyway.- If the body of the task is also monitoring the cancellation token and throws an
OperationCanceledException
containing that token (which is whatThrowIfCancellationRequested
does), then when the task sees thatOperationCanceledException
, it checks whether theOperationCanceledException
's token matches the Task's token. If it does, that exception is viewed as an acknowledgement of cooperative cancellation and theTask
transitions to theCanceled
state (rather than theFaulted
state).
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:
In certain situations in Parallel Extensions and in other systems, it is necessary to wake up a blocked method for reasons that aren't due to explicit cancellation by a user. For example, if one thread is blocked on
blockingCollection.Take()
due to the collection being empty and another thread subsequently callsblockingCollection.CompleteAdding()
, then the first call should wake up and throw anInvalidOperationException
to represent an incorrect usage.
Cancellation in Parallel Extensions