Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is HttpClient safe to use concurrently?

People also ask

Is HttpClient thread safe?

HttpClient is fully thread-safe when used with a thread-safe connection manager such as MultiThreadedHttpConnectionManager.

Should we create a new single instance of HttpClient for all requests?

The correct way as per the post is to create a single instance of HttpClient as it helps to reduce waste of sockets.

What happens if you don't dispose HttpClient?

Answer when NOT using HttpClientFactory: Generally, you don't want to dispose of HttpClient unless it's used very infrequently. Regular creation and disposal may lead to socket exhaustion.

Should I reuse HttpClient?

NET documentation for HttpClient: HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.


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

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


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.