title: .NET Threading - HttpWebRequest BeginGetResponse + AutoResetEvent
body: <p>I would like to know which approach among the two is a better implementation ?
  I need to create a web request which can range between 200ms to 5 seconds. I need the html response to proceed - so need to block on the main thread.</p>
  
  <p><strong>First Approach</strong></p>
  
  <pre><code>string GetResponse()
  {
  
      HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
      IAsyncResult result = request.BeginGetResponse(null, null);    
  
  using (HttpWebResponse httpResponse = (HttpWebResponse)request.EndGetResponse(result))
  {
      using (Stream dataStream = httpResponse.GetResponseStream())
      {
          StreamReader reader = new StreamReader(dataStream);
          response = reader.ReadToEnd();
      }
  }
  </code></pre>
  
  <p><strong>Second Approach</strong></p>
  
  <pre><code>string response = string.Empty;
  AutoResetEvent waitHandle = null;
  void GetResponse(string url)
  {
      waitHandle = new AutoResetEvent(false);
      try
      {
          HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
          IAsyncResult asyncResult = request.BeginGetResponse(Callback, request);
  
          waitHandle.WaitOne();
      }
      catch { }
      finally
      {
          waitHandle.Close();
      }
  }
  
      void Callback(IAsyncResult asyncResult)      
      {           
  
  HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
              try
              {
                  using (HttpWebResponse httpResponse = (HttpWebResponse)request.EndGetResponse(asyncResult))
                  {
                      if (httpResponse.StatusCode == HttpStatusCode.OK)
                      {
                          using (Stream dataStream = httpResponse.GetResponseStream())
                          {
                              StreamReader reader = new StreamReader(dataStream);
                              response = reader.ReadToEnd();
                          }
                      }
                  }
              }
              catch { }
              finally
              {
                  waitHandle.Set();
              }
          }
  </code></pre>