Thursday, September 1, 2016

Don’t dispose your HttpClient

.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…

1 comment:

Anonymous said...

When you are using a single instance of HttpClient DNS changes are not honoured. This can become an issue if the deployment rollout strategy of the URI, you are dependent on, changes its DNS settings (e.g. deployments in the cloud). This is an interesting read: http://byterot.blogspot.be/2016/07/singleton-httpclient-dns.html