title: HttpClient - Send a batch of requests
body: <p>I want to iterate a batch of requests, sending each one of them to an external API using HttpClient class.</p>
  
  <pre><code>  foreach (var MyRequest in RequestsBatch)
    {
              try
              {
                  HttpClient httpClient = new HttpClient();
                  httpClient.Timeout = TimeSpan.FromMilliseconds(5);
                  HttpResponseMessage response = await httpClient.PostAsJsonAsync&lt;string&gt;(string.Format("{0}api/GetResponse", endpoint), myRequest);
                  JObject resultResponse = await response.Content.ReadAsAsync&lt;JObject&gt;();
              }
              catch (Exception ex)
              {
                  continue;
              }
   }
  </code></pre>
  
  <p>The context here is I need to set a very small timeout value, so in case the response takes more than that time, we simply get the "Task was cancelled" exception and continue iterating.</p>
  
  <p>Now, in the code above, comment these two lines:</p>
  
  <pre><code>                HttpResponseMessage response = await httpClient.PostAsJsonAsync&lt;string&gt;(string.Format("{0}api/GetResponse", endpoint), myRequest);
                  resultResponse = await response.Content.ReadAsAsync&lt;JObject&gt;();
  </code></pre>
  
  <p>The iteration ends very fast. Uncomment them and try again. It takes a lot of time. </p>
  
  <p>I wonder if calling PostAsJsonAsync/ReadAsAsync methods with await takes more time than the timeout value?</p>
  
  <p>Based on the answer below, supposing it will create different threads, we have this method:</p>
  
  <pre><code>  public Task&lt;JObject&gt; GetResponse(string endPoint, JObject request, TimeSpan timeout)
      {
          return Task.Run(async () =&gt;
          {
              try
              {
                  HttpClient httpClient = new HttpClient();
                  httpClient.Timeout = TimeSpan.FromMilliseconds(5);
                  HttpResponseMessage response = await httpClient.PostAsJsonAsync&lt;string&gt;(string.Format("{0}api/GetResponse", endPoint), request).WithTimeout&lt;HttpResponseMessage&gt;(timeout);
                  JObject resultResponse = await response.Content.ReadAsAsync&lt;JObject&gt;().WithTimeout&lt;JObject&gt;(timeout);
                  return resultResponse;
              }
              catch (Exception ex)
              {
                  return new JObject() { new JProperty("ControlledException", "Invalid response. ")};
              }
          });
      }
  </code></pre>
  
  <p>An exception is raised there and the JObject exception should be returned, very fast, however, if using httpClient methods, even if it raises the exception it takes a lot of time. Is there a behind the scenes processing affecting the Task even if the return value was a simple exception JObject?</p>
  
  <p>If yes, which another approach could be used to send a batch of requests to an API in a very fast way?</p>