title: Using a CancellationToken to cancel a task without explicitly checking within the task?
body: <p><strong>Background:</strong></p>
  
  <p>I have a web application which kicks off long running (and stateless) tasks:</p>
  
  <pre class="lang-cs prettyprint-override"><code>var task = Task.Run(() =&gt; await DoWork(foo))
  
  task.Wait();
  </code></pre>
  
  <p>Because they are long running, I need to be able to cancel them from a separate web request. </p>
  
  <p>For this, I would like to use a CancellationToken and just throw an exception as soon as the token is canceled. However, from what I've read, Task Cancellation is <a href="https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation" rel="noreferrer">cooperative</a>, meaning the code the task is running must explicitly check the token to see if a cancellation request has been made (for example <code>CancellationToken.ThrowIfCancellation()</code>)</p>
  
  <p>I would like to avoid checking <code>CancellationToken.ThrowIfCancellation()</code> all over the place, since the task is quite long and goes through many functions. I think I can accomplish what I want creating an explicit <code>Thread</code>, but I would really like to avoid manual thread management. That said...</p>
  
  <p><strong>Question:</strong>
  Is it possible to automatically throw an exception in the task when it has been canceled, and if not, are there any good alternatives (patterns, etc.) to reduce polluting the code with <code>CancellationToken.ThrowIfCancellation()</code>?</p>
  
  <p>I'd like to avoid something like this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>async Task&lt;Bar&gt; DoWork(Foo foo)
  {
      CancellationToken.ThrowIfCancellation()
  
      await DoStuff1();
  
      CancellationToken.ThrowIfCancellation()
  
      await DoStuff2();
  
      CancellationToken.ThrowIfCancellation()
  
      await DoStuff3();
  ...
  }
  </code></pre>
  
  <hr>
  
  <p>I feel that this question is sufficiently different from <a href="https://stackoverflow.com/questions/21912533/canceling-await-tasks-without-explicit-checks">this one</a> because I'm explicitly asking for a way to minimize calls to check the cancellation token, to which the accepted answer responds "Every now and then, inside the functions, call token.ThrowIfCancellationRequested()"</p>