You’re using HttpClient wrong and it is destabilizing your software | ASP.NET Monsters
Posted by jpluimers on 2026/09/16
Reminder to self as I see see people disposing [Wayback/Archive] HttpClient Class (System.Net.Http) instances: [Wayback/Archive] You’re using HttpClient wrong and it is destabilizing your software | ASP.NET Monsters
HttpClientis different. Although it implements theIDisposableinterface it is actually a shared object. This means that under the covers it is reentrant and thread safe. Instead of creating a new instance ofHttpClientfor each execution you should share a single instance ofHttpClientfor the entire lifetime of the application.…
Huh, that’s weird…the application has exited and yet there are still a bunch of these connections open to the Azure machine which hosts the ASP.NET Monsters website. They are in the
TIME_WAITstate which means that the connection has been closed on one side (ours) but we’re still waiting to see if any additional packets come in on it because they might have been delayed on the network somewhere.…
If we share a single instance of
HttpClientthen we can reduce the waste of sockets by reusing them
The second part of the quote is what happens if you keep instantiating and disposing HttpClient instances. Instead, use a global instance and let it pool connections as described in the above post.
It is based on [Wayback/Archive] performance-optimization/ImproperInstantiation/docs/ImproperInstantiation.md at 465514674354c8f833c73882f7405ac22c4fd437 · mspnp/performance-optimization · GitHub (an old commit as the document by now has vanished) and [Wayback/Archive] performance-optimization/ImproperInstantiation/docs/LoadTesting.md at master · mspnp/performance-optimization · GitHub.
–jeroen






Leave a Comment