title: How can I use WaitHandle awaiting completion of an asynchronous call?
body: <p>Consider this code:        </p>
  
  <pre><code>class Program
          {
              static void Main(string[] args)
              {
                  Master master = new Master();
                  master.Execute();
              }
          }
  
      class TestClass
      {
          public void Method(string s)
          {
              Console.WriteLine(s);
              Thread.Sleep(5000);
              Console.WriteLine("End Method()");
          }
      }
      class Master
      {
          private readonly TestClass test = new TestClass();
  
          public void Execute()
          {
              Console.WriteLine("Start main thread..");
              Action&lt;String&gt; act = test.Method;
              IAsyncResult res = act.BeginInvoke("Start Method()..", x =&gt;
              {
                  Console.WriteLine("Start Callback..");
                  act.EndInvoke(x);
                  Console.WriteLine("End Callback");
              }, null);
              Console.WriteLine("End main thread");
              Console.ReadLine();
          }
      }
  </code></pre>
  
  <p>We have result:</p>
  
  <pre><code>Start main thread..
  End main thread
  Start Method()..
  End Method()
  Start Callback..
  End Callback
  </code></pre>
  
  <p>So, I want result:</p>
  
  <pre><code>Start main thread..    
  Start Method()..
  End Method()
  Start Callback..
  End Callback
  End main thread
  </code></pre>
  
  <p>How can I wait <code>async</code> in this code? I checked MSDN article <a href="http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx" rel="nofollow noreferrer">"Calling Synchronous Methods Asynchronously"</a> and found this:</p>
  
  <p>After calling <code>BeginInvoke</code> you can do the following:</p>
  
  <ul>
  <li>Do some work and then call <code>EndInvoke</code> to block until the call
  completes.</li>
  <li>Obtain a <code>WaitHandle</code> using the <code>IAsyncResultAsyncWaitHandle</code><br>
  property, use its <code>WaitOne</code> method to block execution until the<br>
  <code>WaitHandle</code> is signaled, and then call <code>EndInvoke</code>.</li>
  <li>Poll the    <code>IAsyncResult</code> returned by <code>BeginInvoke</code> to determine when
  the    asynchronous call has completed, and then call <code>EndInvoke</code>.</li>
  <li>Pass a    delegate for a callback method to <code>BeginInvoke</code>. The method
  is executed    on a <code>ThreadPool</code> thread when the asynchronous call
  completes. The    callback method calls <code>EndInvoke</code>.</li>
  </ul>
  
  <p>I think better variant for me this second. But how implement this? In particular I'm interested overload <code>WaitOne()</code> (<a href="http://msdn.microsoft.com/en-gb/library/system.threading.waithandle.waitone.aspx" rel="nofollow noreferrer">Blocks the current thread until the current WaitHandle receives a signal</a>). How correctly do it? I mean the common pattern in this case.</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Now I use <code>Task&lt;T&gt;</code>:   </p>
  
  <pre><code> class Program
      {
          static void Main(string[] args)
          {
              Master master = new Master();
              master.Execute();
          }
      }
  
      class WebService
      {
          public int GetResponse(int i)
          {
              Random rand = new Random();
              i = i + rand.Next();
              Console.WriteLine("Start GetResponse()");
              Thread.Sleep(3000);
              Console.WriteLine("End GetResponse()");
              return i;
          }
  
          public void SomeMethod(List&lt;int&gt; list)
          {
              //Some work with list        
              Console.WriteLine("List.Count = {0}", list.Count);
          }
      }
      class Master
      {
          private readonly WebService webService = new WebService();
  
          public void Execute()
          {
              Console.WriteLine("Start main thread..");
              List&lt;int&gt; listResponse = new List&lt;int&gt;();
              for (int i = 0; i &lt; 5; i++)
              {
                  var task = Task&lt;int&gt;.Factory.StartNew(() =&gt; webService.GetResponse(1))
                      .ContinueWith(x =&gt;
                      {
                          Console.WriteLine("Start Callback..");
                          listResponse.Add(x.Result);
                          Console.WriteLine("End Callback");
                      });
              }
              webService.SomeMethod(listResponse);
              Console.WriteLine("End main thread..");
              Console.ReadLine();
          }
      }
  </code></pre>
  
  <p>Main problem this is <code>SomeMethod()</code> gets empty <code>list</code>.</p>
  
  <p>Result:
  <img src="https://i.stack.imgur.com/zosFk.png" alt="enter image description here"></p>
  
  <p>Now I have monstrous solution :(</p>
  
  <pre><code> public void Execute()
          {
              Console.WriteLine("Start main thread..");
              List&lt;int&gt; listResponse = new List&lt;int&gt;();
              int count = 0;
              for (int i = 0; i &lt; 5; i++)
              {
                  var task = Task&lt;int&gt;.Factory.StartNew(() =&gt; webService.GetResponse(1))
                      .ContinueWith(x =&gt;
                      {
                          Console.WriteLine("Start Callback..");
                          listResponse.Add(x.Result);
                          Console.WriteLine("End Callback");
                          count++;
                          if (count == 5)
                          {
                              webService.SomeMethod(listResponse);
                          }
                      });
  
              }
              Console.WriteLine("End main thread..");
              Console.ReadLine();
          }
  </code></pre>
  
  <p>Result:</p>
  
  <p><img src="https://i.stack.imgur.com/Wtspl.png" alt="enter image description here"></p>
  
  <p>That's what I need to wait for the asynchronous call. How can I use <code>Wait</code> for <code>Task</code> here?</p>
  
  <p><strong>UPDATE 2:</strong></p>
  
  <pre><code>class Master
  {
      private readonly WebService webService = new WebService();
      public delegate int GetResponseDelegate(int i);
  
      public void Execute()
      {
          Console.WriteLine("Start main thread..");
          GetResponseDelegate act = webService.GetResponse;
          List&lt;int&gt; listRequests = new List&lt;int&gt;();
          for (int i = 0; i &lt; 5; i++)
          {
              act.BeginInvoke(1, (result =&gt;
              {                    
                  int req = act.EndInvoke(result);
                  listRequests.Add(req);
              }), null);  
          }
  
          webService.SomeMethod(listRequests);
          Console.WriteLine("End main thread..");
          Console.ReadLine();
      }
  }
  </code></pre>