title: How to wait for a BackgroundWorker to cancel?
body: <p>Consider a <em>hypothetical</em> method of an object that does stuff for you:</p>
  
  <pre><code>public class DoesStuff
  {
      BackgroundWorker _worker = new BackgroundWorker();
  
      ...
  
      public void CancelDoingStuff()
      {
          _worker.CancelAsync();
  
          //todo: Figure out a way to wait for BackgroundWorker to be cancelled.
      }
  }
  </code></pre>
  
  <p>How can one wait for a BackgroundWorker to be done?</p>
  
  <hr>
  
  <p>In the past people have tried:</p>
  
  <pre><code>while (_worker.IsBusy)
  {
      Sleep(100);
  }
  </code></pre>
  
  <p>But <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1819196&amp;SiteID=1" rel="noreferrer">this deadlocks</a>, because <code>IsBusy</code> is not cleared until after the <code>RunWorkerCompleted</code> event is handled, and that event can't get handled until the application goes idle. The application won't go idle until the worker is done. (Plus, it's a busy loop - disgusting.)</p>
  
  <p>Others have add suggested kludging it into:</p>
  
  <pre><code>while (_worker.IsBusy)
  {
      Application.DoEvents();
  }
  </code></pre>
  
  <p>The problem with that is that is <code>Application.DoEvents()</code> causes messages currently in the queue to be processed, which cause re-entrancy problems (.NET isn't re-entrant).</p>
  
  <p>I would hope to use some solution involving Event synchronization objects, where the code <strong>waits</strong> for an event - that the worker's <code>RunWorkerCompleted</code> event handlers sets. Something like:</p>
  
  <pre><code>Event _workerDoneEvent = new WaitHandle();
  
  public void CancelDoingStuff()
  {
      _worker.CancelAsync();
      _workerDoneEvent.WaitOne();
  }
  
  private void RunWorkerCompletedEventHandler(sender object, RunWorkerCompletedEventArgs e)
  {
      _workerDoneEvent.SetEvent();
  }
  </code></pre>
  
  <p>But I'm back to the deadlock: the event handler can't run until the application goes idle, and the application won't go idle because it's waiting for an Event.</p>
  
  <p>So how can you wait for an BackgroundWorker to finish?</p>
  
  <hr>
  
  <p><strong>Update</strong>
  People seem to be confused by this question. They seem to think that I will be using the BackgroundWorker as:</p>
  
  <pre><code>BackgroundWorker worker = new BackgroundWorker();
  worker.DoWork += MyWork;
  worker.RunWorkerAsync();
  WaitForWorkerToFinish(worker);
  </code></pre>
  
  <p>That is <em>not</em> it, that is <em>not</em> what I'm doing, and that is <em>not</em> what is being asked here. If that were the case, there would be no point in using a background worker.</p>