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
Taskstarting to execute, theTaskwon’t execute. Rather than transitioning to
Running, 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
OperationCanceledExceptioncontaining that token
(which is whatThrowIfCancellationRequesteddoes), 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 theTasktransitions to theCanceled
state (rather than theFaultedstate).