Should I cache and reuse HttpClient created from HttpClientFactory?

前端 未结 2 1331
无人及你
无人及你 2021-02-13 04:19

We can read here YOU\'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE that we should not create and dispose HttpClient for each http request. Instead, it should

2条回答
  •  一向
    一向 (楼主)
    2021-02-13 05:04

    HttpClient is only IDisposable because its HttpMessageHandler is IDisposable. In reality, it's the HttpMessageHandler which should be long-lived.

    HttpClientFactory works by keeping a long-lived HttpMessageHandler internally. Whenever you ask for a HttpClient, it uses the long-lived HttpMessageHander, and tells the HttpClient not to dispose it when the HttpClient is disposed.

    You can see that on GitHub:

    public HttpClient CreateClient(string name)
    {
        // ...
    
        // Get a cached HttpMessageHandler
        var handler = CreateHandler(name);
    
        // Give it to a new HttpClient, and tell it not to dispose it
        var client = new HttpClient(handler, disposeHandler: false);
    
        // ...
    
        return client;
    }
    

    So, technically it doesn't matter whether you cache the HttpClient or dispose it straight away - disposing it doesn't do anything (because it's been told not to dispose its HttpClientHandler, as that's managed by the HttpClientFactory).

    Regarding disposing the HttpClient, MSDN says:

    Disposal of the client isn't required. Disposal cancels outgoing requests and guarantees the given HttpClient instance can't be used after calling Dispose. IHttpClientFactory tracks and disposes resources used by HttpClient instances. The HttpClient instances can generally be treated as .NET objects not requiring disposal.

    Keeping a single HttpClient instance alive for a long duration is a common pattern used before the inception of IHttpClientFactory. This pattern becomes unnecessary after migrating to IHttpClientFactory.

    I suspect the SocketExceptions you're seeing have a different cause. Perhaps ask a new question focussed on them?

提交回复
热议问题