.net HttpClient 并发使用是否安全?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11178220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is HttpClient safe to use concurrently?
提问by Alex K
In all the examples I can find of usages of HttpClient, it is used for one off calls. But what if I have a persistent client situation, where several requests can be made concurrently? Basically, is it safe to call client.PostAsyncon 2 threads at once against the same instance of HttpClient.
在我能找到的所有使用 的示例中HttpClient,它用于一次性调用。但是,如果我有一个持久的客户端情况,可以同时发出多个请求呢?基本上,client.PostAsync针对同一个HttpClient.
I am not really looking for experimental results here. As a working example could simply be a fluke (and a persistent one at that), and a failing example can be a misconfiguration issue. Ideally I'm looking for some authoritative answer to the question of concurrency handling in HttpClient.
我并不是真的在这里寻找实验结果。作为一个工作示例可能只是一个侥幸(和一个持久的),一个失败的例子可能是一个错误的配置问题。理想情况下,我正在寻找有关 HttpClient 中并发处理问题的权威答案。
回答by Marcel N.
According to MSDN, since .NET 4.5 The following instance methods are thread safe(thanks @ischell):
根据 MSDN,自 .NET 4.5 以下实例方法是线程安全的(感谢@ischell):
CancelPendingRequests
DeleteAsync
GetAsync
GetByteArrayAsync
GetStreamAsync
GetStringAsync
PostAsync
PutAsync
SendAsync
回答by muruge
Here is another articlefrom Henrik F. Nielsen about HttpClient where he says:
这是Henrik F. Nielsen 关于 HttpClient 的另一篇文章,他说:
"The default HttpClient is the simplest way in which you can start sending requests. A single HttpClient can be used to send as many HTTP requests as you want concurrentlyso in many scenarios you can just create one HttpClient and then use that for all your requests."
"默认的 HttpClient 是您开始发送请求的最简单方式。单个 HttpClient 可用于同时发送任意数量的 HTTP 请求,因此在许多情况下,您只需创建一个 HttpClient,然后将其用于所有请求.”
回答by Alex K
Found one MSDN forum postby Henrik F. Nielsen (one of HttpClient's principal Architects).
找到了 Henrik F. Nielsen(HttpClient 的主要架构师之一)的一篇MSDN 论坛帖子。
Quick summary:
快速总结:
- If you have requests that are related (or won't step on eachother) then using the same HttpClient makes a lot of sense.
- In genral I would recommend reusing HttpClient instances as much as possible.
- 如果您有相关的请求(或不会相互影响),那么使用相同的 HttpClient 很有意义。
- 一般来说,我建议尽可能多地重用 HttpClient 实例。

