Disposing HttpClient gives port exception

sourabh mishra
2 min readMar 24, 2018

--

Recently while writing an asynchronous code which frequently calls an API, I was getting this PORT EXCEPTION:

One or more errors occurred. An error occurred while sending the request. Unable to connect to the remote server Only one usage of each socket address (protocol/network address/port) is normally permitted 127.0.0.1:53956 StackTrace: at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task`1.get_Result()

On searching on web, i found some weird answers to increase port in registry and decreasing the timeout period of request.
But after 2 hours of debugging and frustration, i figured out the root cause of the issue.

WHAT WAS THE ISSUE:

I found out that the main reason of getting this issue is MSDN documentation about using keyword and to use it for disposing the objects. Generally we use using statement to create the object. once the scope of the using statement ends CLR cleans up the created object. But this is the catch with HttpClient. While creating the instance of HttpClient it basically acquires a port and set a ESTABLISHED status for that port. Once clients get the response from server, HttpClient changes the state to TIME_WAIT status. In TIME_WAIT state the connection will get closed from the client side, but socket still waits for any additional packet that got delayed or got stuck on network. Now though HttpClient object has been disposed, but the port is still in non-usable condition for a new request. So if you have a chatty system where you make API calls very frequently then you might be exhausted with your available port numbers.

UNDERSTAND FROM THE CODE:

In this piece of code I am making 1000 request. So basically it will create the httpclient object 1000 times and each request will acquire a port. So you might not have that many available port in the system which will lead to the “PORT Exception” issue.

HOW TO FIX:

I think HttpClient is one of the class in .Net which need a different attention in order to create its object. We should share the httpClient object for any N request which takes same request header. This will greatly improve the performance by resuing the same sockets and reducing the wastage of sockets.

FINAL NOTE:

Out of socket exception doesn’t seems to very big issue until you start building a system which requires lot of back and forth call with client and server. So always make HttpClient as static and ensure not to dispose your Httpclient object until you need to change the behavior of your http request.

--

--