You are using HttpClient incorrectly

Ron Jonkers
4 min readJan 16, 2021

If you are a C# developer, I am sure that at one point or another you have used HttpClient. Another thing that I am sure of is that you have been using it incorrectly.

Why we use HttpClient incorrectly

HttpClient is being misused as often as it is, because of two reasons:

  1. We’ve been taught to instantiate disposable objects in a using statement
  2. The majority of tutorials teach us the wrong way

Manually disposing is a no go

If we look at the HttpClient class, we see that it extends the HttpMessageInvoker class, which in turn implements IDisposable. One thing that we learn at a pretty early stage as C# developers is that disposable objects need to be instantiated within a using statement. Doing this ensures that the object is disposed once we break out of the using statement. Although this is a good practice in the majority of situations, the HttpClient is an exception to this rule. To quote the official documentation:

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.

--

--

Ron Jonkers

Husband, father, crypto enthusiast and software developer.