Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You need this argument if you want to cancel the Task. If you're application doesn't support or require cancellation then you could just say</p> <pre><code>Task.Factory.StartNew(() =&gt; { ... }); </code></pre> <p>Note that cancellation is cooperative so your code must poll for cancellation and respond accordingly.</p> <p>For example:</p> <pre><code>CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; Task myTask = Task.Factory.StartNew(() =&gt; { for (...) { token.ThrowIfCancellationRequested(); // Body of for loop. } }, token); // ... elsewhere ... cts.Cancel(); </code></pre> <p>You have to pass the cancellation token to the method otherwise it's not attached to the task. The code within method is only using the token to respond to cancelation, either throwing or using the IsCancellationRequested to shut down. Although a task could cancel itself from within the lambda I guess. The task itself needs the token too.</p> <p>here's some further clarification:</p> <blockquote> <p>Passing a token into StartNew associates the token with the Task. 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 OCE, it checks whether the OCE'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).</p> </blockquote> <p>From <a href="http://social.msdn.microsoft.com/Forums/en/parallelextensions/thread/c2f614f6-c96c-4821-84cc-050b21aaee45" rel="nofollow">http://social.msdn.microsoft.com/Forums/en/parallelextensions/thread/c2f614f6-c96c-4821-84cc-050b21aaee45</a></p> <p>See general discussion of cancellation here:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ff963549.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ff963549.aspx</a> for further discussion.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload