title: How to properly start and cancel a task.
body: <p>I can't seem to wrap my head around how to properly start a task and cancel it. I've changed my code to be more simple to understand my issue and pasted it below (I've also added some comments). The <code>SubscribeToReport</code> method is called first - it contains an await <code>runReportTask</code> which from my understanding will just start the <code>runReportTask</code> method, wait for it to complete execution, then resume executing the code that appear after the <code>await</code>. </p>
  
  <p>Inside <code>runReportTask</code> I create a CancellationTokenSource and start a new task using <code>Task.Factory.StartNew()</code>. Inside the task, there is a while loop that performs processing as long as the task hasn't been canceled. From my understanding, if <code>cancellationToken.IsCancellationRequested</code> is ever true, the else within my while loop will run and the task will stop. After that, I expect <code>SubscribeToReport()</code> to continue execution - this does not happen, and it doesn't ever seem like my code does anything when I call <code>cancellationTokenSource.Cancel()</code> in <code>StopReportTask()</code> . What am I doing wrong? I've been at this for a while and I just can't seem to wrap my head around how this is supposed to work. </p>
  
  <pre><code>private async static void SubscribeToReport()
  {
      Console.WriteLine("Waiting for task to finish or cancel...");
  
      await runReportTask();
  
      Console.WriteLine("Task has finished or was canceled."); // THIS LINE NEVER EXECUTES
  }
  
  private static CancellationTokenSource cancellationTokenSource;
  private static CancellationToken cancellationToken;
  private bool moreToDo = true;
  private static Task runReportTask()
  {
      cancellationTokenSource = new CancellationTokenSource();
      cancellationToken = cancellationTokenSource.Token;
  
      return Task.Factory.StartNew(() =&gt;
      {
          // Were we already canceled?
          cancellationToken.ThrowIfCancellationRequested();
  
          while(moreToDo == true)
          {
              if(!cancellationToken.IsCancellationRequested)
              {
                  // Do important code here
              }
              else{
                  Console.WriteLine("Task canceled."); // THIS LINE NEVER EXECUTES WHEN CALLING StopReportTask() below
                  cancellationToken.ThrowIfCancellationRequested();
                  break;
              }
          }
  
      }, cancellationToken);
  }
  
  // This method is called from another source file
  private void StopReportTask()
  {
      Console.WriteLine("Stopping report task...");
  
      cancellationTokenSource.Cancel();
  }
  </code></pre>