Is HttpClient safe to use concurrently?

.NetC# 4.0ConcurrencyDotnet Httpclient

.Net Problem Overview


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.

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.

.Net Solutions


Solution 1 - .Net

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

Solution 2 - .Net

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."

Solution 3 - .Net

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex KView Question on Stackoverflow
Solution 1 - .NetMarcel N.View Answer on Stackoverflow
Solution 2 - .NetmurugeView Answer on Stackoverflow
Solution 3 - .NetAlex KView Answer on Stackoverflow