title: Web Api + HttpClient: An asynchronous module or handler completed while an asynchronous operation was still pending
body: <p>I'm writing an application that proxies some HTTP requests using the ASP.NET Web API and I am struggling to identify the source of an intermittent error.
  It seems like a race condition... but I'm not entirely sure.</p>
  
  <p>Before I go into detail here is the general communication flow of the application:</p>
  
  <ul>
  <li><strong>Client</strong> makes a HTTP request to <strong>Proxy 1</strong>. </li>
  <li><strong>Proxy 1</strong> relays the contents of the HTTP request to Proxy 2</li>
  <li><strong>Proxy 2</strong> relays the contents of the HTTP request to the Target Web Application</li>
  <li><strong>Target Web App</strong> responds to the HTTP request and the response is streamed (chunked transfer) to Proxy 2</li>
  <li><strong>Proxy 2</strong> returns the response to <strong>Proxy 1</strong> which in turn responds to the original calling <strong>Client</strong>.</li>
  </ul>
  
  <p>The Proxy applications are written in ASP.NET Web API RTM using .NET 4.5.
  The code to perform the relay looks like so:
  </p>
  
  <pre><code>//Controller entry point.
  public HttpResponseMessage Post()
  {
      using (var client = new HttpClient())
      {
          var request = BuildRelayHttpRequest(this.Request);
  
          //HttpCompletionOption.ResponseHeadersRead - so that I can start streaming the response as soon
          //As it begins to filter in.
          var relayResult = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).Result;
  
          var returnMessage = BuildResponse(relayResult);
          return returnMessage;
      }
  }
  
  private static HttpRequestMessage BuildRelayHttpRequest(HttpRequestMessage incomingRequest)
  {
      var requestUri = BuildRequestUri();
      var relayRequest = new HttpRequestMessage(incomingRequest.Method, requestUri);
      if (incomingRequest.Method != HttpMethod.Get &amp;&amp; incomingRequest.Content != null)
      {
         relayRequest.Content = incomingRequest.Content;
      }
  
      //Copies all safe HTTP headers (mainly content) to the relay request
      CopyHeaders(relayRequest, incomingRequest);
      return relayRequest;
  }
  
  private static HttpRequestMessage BuildResponse(HttpResponseMessage responseMessage)
  {
      var returnMessage = Request.CreateResponse(responseMessage.StatusCode);
      returnMessage.ReasonPhrase = responseMessage.ReasonPhrase;
      returnMessage.Content = CopyContentStream(responseMessage);
  
      //Copies all safe HTTP headers (mainly content) to the response
      CopyHeaders(returnMessage, responseMessage);
  }
  
  private static PushStreamContent CopyContentStream(HttpResponseMessage sourceContent)
  {
      var content = new PushStreamContent(async (stream, context, transport) =&gt;
              await sourceContent.Content.ReadAsStreamAsync()
                              .ContinueWith(t1 =&gt; t1.Result.CopyToAsync(stream)
                                  .ContinueWith(t2 =&gt; stream.Dispose())));
      return content;
  }
  </code></pre>
  
  <p>The error that occurs intermittently is:</p>
  
  <blockquote>
    <p>An asynchronous module or handler completed while an asynchronous operation was still pending.</p>
  </blockquote>
  
  <p>This error usually occurs on the first few requests to the proxy applications after which the error is not seen again.</p>
  
  <p>Visual Studio never catches the Exception when thrown.
  But the error can be caught in the Global.asax Application_Error event.
  Unfortunately the Exception has no Stack Trace.</p>
  
  <p>The proxy applications are hosted in Azure Web Roles.</p>
  
  <p>Any help identifying the culprit would be appreciated.</p>