title: How to check if previous task is still running and stop/cancel it?
body: <p>I have a background task that I run in the following way.</p>
  
  <p>This is in an attached behavior on a textbox text changed event.</p>
  
  <p>What I would like is if the text is changed and then changed again, on the second change check if the previous task is still running, if so, stop it and continue with the latest one.</p>
  
  <pre><code>public class FindTextChangedBehavior : Behavior&lt;TextBox&gt;
  {
      protected override void OnAttached()
      {
          base.OnAttached();
          AssociatedObject.TextChanged += OnTextChanged;
      }
  
      protected override void OnDetaching()
      {
          AssociatedObject.TextChanged -= OnTextChanged;
          base.OnDetaching();
      }
  
      private void OnTextChanged(object sender, TextChangedEventArgs args)
      {
          var textBox = (sender as TextBox);
          if (textBox != null)
          {
              Task.Factory.StartNew(() =&gt;
              {
                  //Do text search on object properties within a DataGrid
                  //and populate temporary ObservableCollection with items.
                  ClassPropTextSearch.init(itemType, columnBoundProperties);
  
                  if (itemsSource != null)
                  {
                      foreach (object o in itemsSource)
                      {
                          if (ClassPropTextSearch.Match(o, searchValue))
                          {
                              tempItems.Add(o);
                          }
                      }
                  }
  
                  //Copy temporary collection to UI bound ObservableCollection 
                  //on UI thread
                  Application.Current.Dispatcher.Invoke(new Action(() =&gt; MyClass.Instance.SearchMarkers = tempItems));
              });
          }
      }
  </code></pre>
  
  <p>[EDIT] I have not tested this yet just a mockup of what might be.</p>
  
  <pre><code>CancellationTokenSource CancellationTokenSource = new CancellationTokenSource();
  
  private void OnTextChanged(object sender, TextChangedEventArgs args)
  {
      var newCts = new CancellationTokenSource();
      var oldCts = Interlocked.Exchange(ref this.CancellationTokenSource, newCts);
  
      if (oldCts != null)
      {
          oldCts.Cancel();
      }
  
      var cancellationToken = newCts.Token;
  
      var textBox = (sender as TextBox);
      if (textBox != null)
      {
          ObservableCollection&lt;Object&gt; tempItems = new ObservableCollection&lt;Object&gt;();
          var ui = TaskScheduler.FromCurrentSynchronizationContext();
  
          var search = Task.Factory.StartNew(() =&gt;
          {
              ClassPropTextSearch.init(itemType, columnBoundProperties);
  
              if (itemsSource != null)
              {
                  foreach (object o in itemsSource)
                  {
                      cancellationToken.ThrowIfCancellationRequested();
                      if (ClassPropTextSearch.Match(o, searchValue))
                      {
                          tempItems.Add(o);
                      }
                  }
              }
          }, cancellationToken);
  
          //Still to be considered.
          //If it gets to here and it is still updating the UI then 
          //what to do, upon SearchMarkers being set below do I cancel
          //or wait until it is done and continue to update again???
          var displaySearchResults = search.ContinueWith(resultTask =&gt;
                       MyClass.Instance.SearchMarkers = tempItems,
                       CancellationToken.None,
                       TaskContinuationOptions.OnlyOnRanToCompletion,
                       ui);
      }
  }
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/zf0ix.jpg" alt="enter image description here"></p>