It's been recommended to reuse the full framework's HttpClientHandler
across multiple requests instead of disposing it every time (because disposing it means the performance hit of closing and re-opening the underlying connection). Does this advice stands true for the brand new world of CurlHandler
and WinHttpHandler
?
Yes.
cc: @davidsh, @cipop
Once you attach the HttpClientHandler
to the HttpClient
via:
c#
var handler = new HttpClientHandler;
var client = new HttpClient(handler);
it is not necessary to Dispose
the handler directly since disposing the client will dispose the handler as well.
But in general, you should share and reuse the HttpClient
. this is the only way to share TCP the pool of TCP connections.
Closing, as I believe the question has been answered. Please re-open if it hasn't. Thanks.
@davidsh @stephentoub what about sharing the same HttpClientHandler
(be it the default or WinHttpHandler
) between different HttpClient
instances with different DefaultRequestHeaders
?
what about sharing the same HttpClientHandler (be it the default or WinHttpHandler) between different HttpClient instances.
That is not recommended at all. The handler is owned by the HttpClient once you create the HttpClient. It is an undefined behavior to share the same handler object between separate client objects.
@davidsh thank you for clarifying. What would you suggest then for such a scenario (shared HttpClient
but different request headers)? I can only think of wrapping HttpClient
with my wrapper that translates all calls to a SendAsync
call with the proper headers. However that's a lot of overloads to implement (GetAsync, DeleteAsync, PostJsonAsync
etc)...
That is not recommended at all.
Why not? If the HttpClient is passed the handler instance along with a bool indicating the HttpClient doesn't own it, what breaks?
Why not? If the HttpClient is passed the handler instance along with a bool indicating the HttpClient doesn't own it, what breaks?
After reviewing this some more, you are correct in that using this form of the HttpClient ctor:
c#
public HttpClient (System.Net.Http.HttpMessageHandler handler, bool disposeHandler);
will mean that the HttpClient object doesn't "own" the handler. So, in theory, you can share the same handler between HttpClient objects.
@davidsh : From you comment above, it seems that this scenario of using same HttpClientHandler with different HttpClient was kind of not tested/expected by .Net team back then.
Did you guys test that scenario after that to say that it is safe to use these two classes in this manner to avoid TCP connection exhaustion in case of heavy load?
Most helpful comment
Why not? If the HttpClient is passed the handler instance along with a bool indicating the HttpClient doesn't own it, what breaks?