Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-using HttpClient but with a different Timeout setting per request?

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).

like image 830
boot4life Avatar asked Oct 22 '17 13:10

boot4life


People also ask

How do I increase HttpClient timeout?

The default value is 100,000 milliseconds (100 seconds). To set an infinite timeout, set the property value to InfiniteTimeSpan. A Domain Name System (DNS) query may take up to 15 seconds to return or time out.

How would you set a timeout on an HTTP request?

Timeouts on http. request() takes a timeout option. Its documentation says: timeout <number> : A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.

What does HttpClient timeout do?

timeout) – the time waiting for data – after establishing the connection; maximum time of inactivity between two data packets. the Connection Manager Timeout (http. connection-manager. timeout) – the time to wait for a connection from the connection manager/pool.

What is the difference between connection timeout and connection request timeout?

request timeout — a time period required to process an HTTP call: from sending a request to receiving a response. connection timeout — a time period in which a client should establish a connection with a server. socket timeout — a maximum time of inactivity between two data packets when exchanging data with a server.


1 Answers

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:

using 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; 
like image 123
Todd Menier Avatar answered Sep 17 '22 09:09

Todd Menier