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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With