title: CancellationToken Behavior
body: <p>I want to understand how the <code>CancellationToken</code> works, and how it cancels tasks.</p>
  <p>For that, I created this example, which uses the same token for both the <code>Task.Run()</code> and the inner method - <code>HelpDoingSomething()</code></p>
  <p>So, I let the task run for 500ms, then I cancel the token, and the result is:</p>
  <p>First printed message: <em>&quot;HelpDoingSomething cancelled&quot;</em> and then <em>&quot;DoSomething cancelled&quot;</em></p>
  <pre class="lang-csharp prettyprint-override"><code>class Program
  {
      static void Main(string[] args)
      {
          var cts = new CancellationTokenSource();
  
          var myClass = new MyClass(cts.Token);
          myClass.DoSomething();
  
          Thread.Sleep(500);
          cts.Cancel();
  
          System.Console.ReadKey();
      }
  }
  
  internal class MyClass
  {
      private CancellationToken token;
  
      public MyClass(CancellationToken token)
      {
          this.token = token;
      }
  
      public void DoSomething()
      {
          Task.Run(() =&gt;
          {
              HelpDoingSomething();
              System.Console.WriteLine(&quot;DoSomething cancelled&quot;);
          }, token);
      }
  
      private void HelpDoingSomething()
      {
          while (!token.IsCancellationRequested)
          {
              //Keep doing something
              System.Console.Write(&quot;.&quot;);
          }
  
          System.Console.WriteLine(&quot;HelpDoingSomething cancelled&quot;);
      }
  }
  </code></pre>
  <p>I know exactly that my method <code>HelpDoingSomething()</code> checks if the cancellationToken was requested on each iteration of the loop.</p>
  <p>My question is how and how often does the <code>Task.Run()</code> method check if a cancellation token is requested?</p>
  <p>Is that possible that <code>Task.Run()</code> will check that before <code>HelpDoingSomething()</code> does, and I will see only one message printed (<em>&quot;DoSomething cancelled&quot;</em>)? This means the logic may not be handled correctly in this method.</p>