title: Best approach to Timeout using HttpWebRequest.BeginGetResponse
body: <p>HttpWebRequest.BeginGetResponse doesn´t respect any Timeout properties from HttpWebRequest(Timeout or ReadWriteTimeout).</p>
  
  <p>I read some approaches to get the same results, but I don't know if it's the best way to do it and if I should use for few calls or I can scale it inside loops(I am doing a webcrawler).</p>
  
  <p>The important thing is, initially my code isn´t async, I just need async because my method should accept a CancellationToken.</p>
  
  <p>My concern is about WaitHandles and ThreadPool.RegisterWaitForSingleObject. It isn´t a daily code then I don´t know if I can have problems in the near future.</p>
  
  <pre><code>private static void HandleCancellation(HttpWebRequest request, IAsyncResult getResponseResult, CancellationToken cancellationToken)
  {
      using (WaitHandle requestHandle = getResponseResult.AsyncWaitHandle)
      {
          ThreadPool.RegisterWaitForSingleObject(requestHandle, TimeoutCallback, request, request.Timeout, true);
  
          //If request finish or cancellation is called
          WaitHandle.WaitAny(new[] {requestHandle, cancellationToken.WaitHandle});
      }
  
      //If cancellation was called
      if (cancellationToken.IsCancellationRequested)
      {
          request.Abort();
          cancellationToken.ThrowIfCancellationRequested();
      }
  }
  </code></pre>
  
  <p>Calling(again, it isn´t async)</p>
  
  <pre><code>IAsyncResult getResponseResult = request.BeginGetResponse(null, null);
  
  HandleCancellation(request, getResponseResult, cancellationToken);
  
  return (HttpWebResponse)request.EndGetResponse(getResponseResult);
  </code></pre>
  
  <p>Reference: <a href="https://stackoverflow.com/questions/6720113/better-approach-in-management-of-multiple-webrequest">Better approach in management of multiple WebRequest</a></p>