是HttpClient的安全同时使用? [英] Is HttpClient safe to use concurrently?

查看:167
本文介绍了是HttpClient的安全同时使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在所有的例子中我能找到的HttpClient用法,它用于一次性呼叫。但是,如果我有一个持续的客户端的情况,其中多个请求可以同时做?基本上,它是安全的呼吁client.PostAsync 2线程同时对HttpClient的的同一个实例。

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.PostAsync on 2 threads at once against the same instance of HttpClient.

我不是真的找的实验结果在这里。作为工作例子可以简单地是一个吸虫(和持久一个在那),和一个失败的例子可以是一个错误配置的问题。理想的情况是我在寻找的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.

推荐答案

<打击> 我想,这一切都在<一个href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.110%29.aspx">MSDN:

I think it's all on MSDN:

任何公共static(在Visual Basic中的Shared)这种类型的成员   线程安全的。所有实例成员都不能保证是线程   安全的。

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

所以,你不能使用两个或多个线程调用同一的HttpClient 实例的任何实例方法。 要么你排队的请求,或者使用多个的HttpClient 实例。

So you cannot use two or more threads to call any instance methods on the same HttpClient instance. Either you queue your requests or use multiple HttpClient instances.

第三个选择是,当然,锁定访问您的单一的HttpClient 实例。但你失去了任何意义的多线程,至少在什么涉及调用这个类。

Third option is, of course, locking access to your single HttpClient instance. But then you lose any multithreading meaning, at least in what concerns calls to this class.

编辑:

按照下面的意见(感谢@ischell),下面的实例方法是线程安全的(所有异步):

As per the comments below (thanks @ischell), the following instance methods are thread safe (all async):

CancelPendingRequests
DeleteAsync
GetAsync
GetByteArrayAsync
GetStreamAsync
GetStringAsync
PostAsync
PutAsync
SendAsync

这篇关于是HttpClient的安全同时使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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