.NET allows you to call out to an HTTP service using the HttpClient object. As the HttpClient implements an IDisposable interface and me being a good boy, I always used the HttpClient inside a using statement:
Turns out that this is, in contrast to most situations where a class implements IDisposable, not a good idea to do with the HttpClient. According to this post by Simon Timms on ASP.NET Monsters, each instance of the HttpClient will create a new socket and hold a connection open for a specific interval. This means if you create new HttpClients fast enought sooner or later, you’ll exhaust the connection pool and end up with the following error message:
Unable to connect to the remote server
System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted.
Instead you should create a single instance of the HttpClient and re-use it everywhere. If you want to learn more, check out Simons post: http://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
And now I have to go. Time to fix this in my code…