C# - Should you reuse your HTTPClient? or dispose it after every request?

I have always been told to reuse the HttpClient throughout the application lifetime for better performance and stability. If you search for why, there are quite a few articles on why this might be a great idea.

According to this article the author faced a socket exhaustion issue - System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted - when disposing the HttpClient in a using statement when he was done using it. When changing the application to use the same static HttpClient and not disposing it, all of his issues went away.

Reading official documentation from microsoft on best practices for calling a web API from a net client we see the following block:

HttpClient is intended to be instantiated once and reused throughout the life of an application. The following conditions can result in SocketException errors:

   * Creating a new HttpClient instance per request.
   * Server under heavy load.
   
Creating a new HttpClient instance per request can exhaust the available sockets.

Reusing the same HttpClient and thereby socket also come with performance gains. Makolyte.com reports a 5.5x increase in speed from subsequent requests when reusing the same instance of the HttpClient.

When reading the above it is apparent that you should reuse the same instance of the HttpClient throughout your applications lifetime. In some cases where you use base addresses you can have one for each base address, but it should not be instantiated for each use. That being said, I have personally seen code bases where the HttpClient was disposed after every use and had no issues. This may be an issue that only surfaces when the HttpClient is used heavily.

I hope you found this post helpful, please leave a comment down below. Also please leave a comment if you have more information on the topic!