title: Best practice for consistently cancelling Async CancellationTokenSource
body: <p>So I have a combobox on my UI that on SelectionChanged it asynchronously goes off to a web service to pull back some information to be displayed on the UI (using the new C#5 async/await keywords).  What I'm looking to do is cancel the current async request before sending a new one; for example if the user uses the keyboard to quickly cycle through all of the combobox items, the SelectionChanged event could fire multiple times (generating multiple async requests) before even the first async request returns.</p>
  
  <p>So my async function that gets called from the combobox's SelectionChanged event looks like this:</p>
  
  <pre><code>public async Task&lt;Connections&gt; ConnectionsAsync()
  {
      return await Task.Factory.StartNew(() =&gt; Connections, _cancellationTokenSource.Token);
  }
  </code></pre>
  
  <p>Where Connections is a property that goes off and hits the web service.  So because the CancellationTokenSource cannot be reused once cancelled, I'm thinking of doing this:</p>
  
  <pre><code>public async Task&lt;Connections&gt; ConnectionsAsync()
  {
      _cancellationTokenSource.Cancel();
      _cancellationTokenSource = new CancellationTokenSource();
      return await Task.Factory.StartNew(() =&gt; Connections, _cancellationTokenSource.Token);
  }
  </code></pre>
  
  <p>The problem though is that sometimes I will be calling Cancel() when there is no async command running (e.g. the first time this function is called); so if I hookup any cancellation event handlers they will get called, even before I have made an async request.</p>
  
  <p>Is there anyway to check if an async request is already running?  Other than me doing something like:</p>
  
  <pre><code>public async Task&lt;Connections&gt; ConnectionsAsync()
  {
      if (_runningAsyncCommand)
          _cancellationTokenSource.Cancel();
      _cancellationTokenSource = new CancellationTokenSource();
      _runningAsyncCommand = true;
      return await Task.Factory.StartNew(() =&gt; Connections, _cancellationTokenSource.Token);
      _runningAsyncCommand = false;
  }
  </code></pre>
  
  <p>I have a few async functions that all use the same CancellationTokenSource, so I would have to implement this "plumbing" in all of those functions.  Is this the best approach? Or is there a better way? </p>
  
  <p>Also, if I expose _cancellationTokenSource publically so that other classes can register cancellation delegates with it, what is the best way to "transfer" these delegates over to the new CancellationTokenSource, since I'm creating a new one every time?</p>
  
  <p>Thanks in advance!</p>