In order to reuse open TCP connections with HttpClient
you have to share a single instance for all requests.
This means that we cannot simply instantiate HttpClient
with different settings (e.g. timeout or headers).
How can we share the connections and use different settings at the same time? This was very easy, in fact the default, with the older HttpWebRequest
and WebClient
infrastructure.
Note, that simply setting HttpClient.Timeout
before making a request is not thread safe and would not work in a concurrent application (e.g. an ASP.NET web site).
Under the hood, HttpClient
just uses a cancellation token to implement the timeout behavior. You can do the same directly if you want to vary it per request:
var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(30));
await httpClient.GetAsync("http://www.google.com", cts.Token);
Note that the default timeout for HttpClient
is 100 seconds, and the request will still be canceled at that point even if you've set a higher value at the request level. To fix this, set a "max" timeout on the HttpClient
, which can be infinite:
httpClient.Timeout = System.Threading.Timeout.InfiniteTimeSpan;