重新使用HttpClient但每个请求有不同的超时设置?

时间:2022-10-14 21:25:04

In order to reuse open TCP connections with HttpClient you have to share a single instance for all requests.

为了重用与HttpClient的开放TCP连接,您必须为所有请求共享一个实例。

This means that we cannot simply instantiate HttpClient with different settings (e.g. timeout or headers).

这意味着我们不能简单地使用不同的设置(例如超时或标头)来实例化HttpClient。

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.

我们如何共享连接并同时使用不同的设置?这很简单,实际上是默认的,使用较旧的HttpWebRequest和WebClient基础结构。

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

注意,在发出请求之前简单地设置HttpClient.Timeout不是线程安全的,并且不能在并发应用程序(例如ASP.NET网站)中工作。

1 个解决方案

#1


22  

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:

在引擎盖下,HttpClient只使用取消令牌来实现超时行为。如果您想根据请求更改它,可以直接执行相同的操作:

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的默认超时为100秒,即使您在请求级别设置了更高的值,该请求仍将在该点取消。要解决此问题,请在HttpClient上设置“max”超时,该超时可以是无限的:

httpClient.Timeout = System.Threading.Timeout.InfiniteTimeSpan;

#1


22  

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:

在引擎盖下,HttpClient只使用取消令牌来实现超时行为。如果您想根据请求更改它,可以直接执行相同的操作:

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的默认超时为100秒,即使您在请求级别设置了更高的值,该请求仍将在该点取消。要解决此问题,请在HttpClient上设置“max”超时,该超时可以是无限的:

httpClient.Timeout = System.Threading.Timeout.InfiniteTimeSpan;