更新时间:2023-01-03 12:00:33
在后台, HttpClient
使用取消令牌来实现超时行为。如果您想根据请求更改它,则可以直接执行以下操作:
var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(30));
等待httpClient.GetAsync( http://www.google.com,cts.Token);
请注意, HttpClient
的默认超时为100秒,即使您在请求级别设置了更高的值,该请求仍会被取消。要解决此问题,请在 HttpClient
上设置最大超时,该超时可以是无限的:
httpClient.Timeout = System.Threading.Timeout.InfiniteTimeSpan;
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;