I am looking at implementing a HttpClient as a static to avoid socket exhaustion. (If using an instance per call, you end up with a socket stuck in TIME_WAIT for 4 minutes, and if you perform enough calls or have enough instances of your application running in parallel, you will run out of sockets). I am also aware of the DNS caching problem that this approach causes and will add the suitable ConnectionLeaseTimeout
.
But my question relates to the one static HttpClient that remains.
The first link shows the following example code:
private static HttpClient Client = new HttpClient();
But being IDisposable, it should be disposed once it is no longer required (ie, during application shutdown)? Whilst it may be unnecessary for a pure HttpClient, what if there is a handler that uses unmanaged resources? How could I call dispose this? Or more specifically, is there an event to which I can subscribe to make sure this occurs?
Edit:
This question differs from the suggested duplicate in two important ways.
- That ticket is asked in the context of httpclient instance per call. Indicating that standard usage is not to dispose after every request is self evidently not what my question was suggesting.
- The phrase
The HttpClient object is intended to live for as long as your application needs to make HTTP requests
implies that after your application no longer needs to make HTTP requests is when the disposal should rather happen. Other questions and resources have indicated that IDisposable is required if the handler has unmanaged resources.
In fact I asked this question after reviewing that and several other SO questions to make sure there was no answer. If my question is a duplicate, terrific, I didn't find it though and importantly the suggested duplicate doesn't address this.