Cancellation token in Task constructor: why?

Passing a CancellationToken into the Task constructor associates it with the task.

Quoting Stephen Toub’s answer from MSDN:

This has two primary benefits:

  1. If the token has cancellation requested prior to the Task starting to execute, the Task won’t execute. Rather than transitioning to
    Running, it’ll immediately transition to Canceled. This avoids the
    costs of running the task if it would just be canceled while running
    anyway.
  2. If the body of the task is also monitoring the cancellation token and throws an OperationCanceledException containing that token
    (which is what ThrowIfCancellationRequested does), then when the task
    sees that OperationCanceledException, it checks whether the OperationCanceledException‘s token matches the Task’s
    token. If it does, that exception is viewed as an acknowledgement of
    cooperative cancellation and the Task transitions to the Canceled
    state (rather than the Faulted state).

Leave a Comment