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).
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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With