HttpClient: you should only use one of them!

This week I ran across a useful tweet by Noel Bundick:
Noel Bundick's tweet

I've done this plenty of times and you probably have too. Because if something implements IDisposable then you should probably wrap it into a using block. The C# language reference states:

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.

Sometimes Dispose() is used for convenience or sugar, but many times it does important work of releasing resources. But ultimately it is important to know how the class is intended to be used. Unfortunately this isn't always clear.

The base docs for HttpClient are sparse. Right now this page does point to a full description of using a web API with HttpClient and it calls out:

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Especially in server applications, creating a new HttpClient instance for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.

The ASP.NET Monsters post about HttpClient that Noel tweeted goes into lots of detail.

The takeaway: In most cases you can get by with a single HttpClient instance for the life of your application. Or you might need to pool some instances. But you should not make repeated use of HttpClient by newing one up for each call.