title: Reusing a BackgroundWorker, cancel and wait for it
body: <p>Suppose you have a search textbox and have a search algorithm attached to the TextChanged event, that runs with a BackgroundWorker. If there comes a new character in the textbox, i need to cancel the previous search and run it again.</p>
  
  <p>I tried using events in between the main thread and the bgw, from <a href="https://stackoverflow.com/q/123661/129103">this previous question</a>, but I still get the error "currently busy and cannot run multiple tasks concurrently"</p>
  
  <pre><code>    BackgroundWorker bgw_Search = new BackgroundWorker();
      bgw_Search.DoWork += new DoWorkEventHandler(bgw_Search_DoWork);
  
      private AutoResetEvent _resetEvent = new AutoResetEvent(false);
  
      private void txtSearch_TextChanged(object sender, EventArgs e)
      {
          SearchWithBgw();
      }
  
      private void SearchWithBgw()
      {
          // cancel previous search
          if (bgw_Search.IsBusy)
          {
              bgw_Search.CancelAsync();
  
              // wait for the bgw to finish, so it can be reused.
              _resetEvent.WaitOne(); // will block until _resetEvent.Set() call made
          }
  
          // start new search
          bgw_Search.RunWorkerAsync();   // error "cannot run multiple tasks concurrently"
      }
  
      void bgw_Search_DoWork(object sender, DoWorkEventArgs e)
      {
          Search(txtSearch.Text, e);
      }
  
      private void Search(string aQuery, DoWorkEventArgs e)
      {
          int i = 1;            
          while (i &lt; 3)             // simulating search processing...
          {
              Thread.Sleep(1000);                           
              i++;
  
              if (bgw_Search.CancellationPending)
              {
                  _resetEvent.Set(); // signal that worker is done
                  e.Cancel = true;
                  return;
              }
          }
      }
  </code></pre>
  
  <p>EDIT To reflect answers. Don´t reuse the BackgroundWorker, create a new one:</p>
  
  <pre><code>    private void SearchWithBgw()
      {   
          if (bgw_Search.IsBusy)
          {
              bgw_Search.CancelAsync();
              _resetEvent.WaitOne(); // will block until _resetEvent.Set() call made
  
              bgw_Search = new BackgroundWorker();
              bgw_Search.WorkerSupportsCancellation = true;
              bgw_Search.DoWork += new DoWorkEventHandler(bgw_Search_DoWork);
          }
  
          bgw_Search.RunWorkerAsync();        
      }
  </code></pre>