同时使用HttpClient是否安全?

在我能找到的所有使用HttpClient的例子中,它用于一次性调用。但是,如果我有一个持续的客户端情况,其中可以同时发出多个请求,该怎么办?基本上,针对HttpClient的同一实例,同时在两个线程上调用client.PostAsync是否安全?

我并不是真的在这里寻找实验结果。因为一个工作的例子可能只是一个侥幸(而且是一个持久的例子),而一个失败的例子可能是配置错误的问题。理想情况下,我正在寻找一些关于HttpClient中并发处理问题的权威答案。

89110 次浏览

According to Microsoft Docs, since .NET 4.5 The following instance methods are thread safe (thanks @ischell):

CancelPendingRequests
DeleteAsync
GetAsync
GetByteArrayAsync
GetStreamAsync
GetStringAsync
PostAsync
PutAsync
SendAsync
PatchAsync

Found one MSDN forum post by Henrik F. Nielsen (one of HttpClient's principal Architects).

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.

Here is another article from Henrik F. Nielsen about HttpClient where he says:

"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 concurrently so in many scenarios you can just create one HttpClient and then use that for all your requests."