title: cancelling C# async function
body: <p><strong>I have the following program:</strong>  </p>
  
  <pre><code>class myClass
  {
      CancellationTokenSource cts;
  
      public string someMethod(){
          someMethodWhichIsAsync("10")
      }
  
      private async Task&lt;string&gt; someMethodWhichIsAsync(string data)
      {
          if(cts != null)
          {
              cts.Cancel();
          }
  
          cts = new CancellationTokenSource();
  
          string myString = await Task.Run(() =&gt; someLoop(data,cts.Token) );
  
          return "success";
      }
  
      private string someLoop(string data, CancellationToken token)
      {
  
              while (True)
              {
                  if (token.IsCancellationRequested == true)
                  {
                      return "Canceled";
                  }
  
                  //Do some work in a continuous loop
  
              }
  
              return "successful end";
  
      }
  }
  </code></pre>
  
  <p>I have placed CancellationTokenSource cts; in the class global scope so that it is available every time any function runs.</p>
  
  <p>However cts.Cancel(); only works if I include it inside the function which runs.</p>
  
  <pre><code>        if (token.IsCancellationRequested == true)
          {
              return "Canceled";
          }
  </code></pre>
  
  <p><strong>Why is this?</strong> None of the example code I found requires this.</p>