Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use one HttpClient instance per request or one to handle all my requests?

I'm creating a client for Rest API and I'm using the HttpClient class. My question is: should I use just one instance to handle all my requests? or should I create a new instance per request? Like:

using (var client = new HttpClient()) {
  ...
}

Is there any recommended practice?

like image 873
dmorganb Avatar asked Jan 29 '13 19:01

dmorganb


People also ask

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

Conclusion. One should use a single instance of HttpClient at application level and avoid create/destroy of it multiple times. Further, this also has better performance with more than 12% improvement based on the load.

Should you 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.

Can HttpClient be Singleton?

Another issue that developers run into is when using a shared instance of HttpClient in long-running processes. In a situation where the HttpClient is instantiated as a singleton or a static object, it fails to handle the DNS changes as described in this issue of the dotnet/runtime GitHub repository.

Should you make HttpClient static?

It is better to use HttpClientFactory instead of using static instance of HttpClient directly. Singleton or static instance of HttpClient doesn't respect DNS changes.


1 Answers

You should try to reuse HttpClient instances as much as possible. The only reason to create a new instance is if you want to configure it differently.

like image 200
Youssef Moussaoui Avatar answered Oct 18 '22 01:10

Youssef Moussaoui