What is the use of passing CancellationToken to Task Class constructor? What is the use of passing CancellationToken to Task Class constructor? multithreading multithreading

What is the use of passing CancellationToken to Task Class constructor?


UPDATE:The following msdn question describes the reason:

Passing a token into StartNew associates the token with the Task.This has two primary benefits:

  1. If the token has cancellationrequested prior to the Task starting to execute, the Task won'texecute. Rather than transitioning to Running, it'll immediatelytransition to Canceled. This avoids the costs of running the task ifit would just be canceled while running anyway.

  2. If the body of thetask is also monitoring the cancellation token and throws anOperationCanceledException containing that token (which is whatThrowIfCancellationRequested does), then when the task sees that OCE,it checks whether the OCE's token matches the Task's token. If itdoes, that exception is viewed as an acknowledgement of cooperativecancellation and the Task transitions to the Canceled state (ratherthan the Faulted state).