title: Wait for multiple methods with callbacks to finish
body: <p>I have multiple asynchronous methods that I need to call and wait for them all to finish.  The asynchronous methods all have callback parameters that execute when the asynchronous processing has finished.  So I'm thinking that I need to put some signalling device in each callback and then wait for all the signals to come before continuing.</p>
  
  <p>After doing some searching I'm thinking I could use a an array of <code>AutoResetEvents</code> and then call <code>WaitHandle.WaitAll</code> to wait for them.  Something like:</p>
  
  <pre><code>WaitHandle[] waitHandles = new WaitHandle[] 
  {
      new AutoResetEvent(false),
      new AutoResetEvent(false)
  };
  
  DoWorkA((callback) =&gt;
  {
      waitHandles[0].Set();
  });
  
  DoWorkB((callback) =&gt;
  {
      waitHandles[1].Set();
  });
  
  // wait for DoWorkA and DoWorkB to finish
  WaitHandles.WaitAll(waitHandles);
  
  // continue with the processing
  </code></pre>
  
  <p>I'd like to know if this is a good way to do it, or if there is a better/simpler method.  I need an solution for .Net 2.0, but I'd also be interested to know what other solutions would be available with a later version of .Net.</p>
  
  <p><strong>EDIT:</strong>
  After trying this code I found it doesn't work.  The UI thread stops at <code>WaitHandles.WaitAll(waitHandles)</code> and the callbacks never run... </p>
  
  <p>Inside the DoWork methods there is code being run asnychronously on a background thread, and then from that background thread I attempt to run the callback through <code>BeginInvoke</code> called on a control from the UI thread.  However, the callback never gets executed on the UI thread.  Any ideas what I'm doing wrong?</p>
  
  <p><strong>EDIT 2:</strong>
  I realized why it doesn't work - the thread calling <code>WaitHandles.WaitAll(waitHandles)</code> is the same thread that the callbacks are attempting to run on (the UI thread).  So of course if the thread is waiting for the signal, the callbacks will never run on that same thread and so <code>Set()</code> will never be called.  The WaitAll(waitHandles) and Set() should work, as long as they are not inteded to be run on the same thread.  I think I need to fix it so that the callbacks run on a background thread while the UI thread waits.  Please let me know if my thinking here is incorrect.</p>