重复使用HttpClient,但每个请求的超时设置不同? [英] Re-using HttpClient but with a different Timeout setting per request?

查看:347
本文介绍了重复使用HttpClient,但每个请求的超时设置不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



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

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

解决方案

在后台, 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;

这篇关于重复使用HttpClient,但每个请求的超时设置不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆