Should HttpClient instances created by HttpClientFactory be disposed?

前端 未结 2 570
再見小時候
再見小時候 2020-12-15 15:33

So, I\'ve registered a named client with the services collection in my Startup.cs:

services.AddHttpClient(someServiceN         


        
2条回答
  •  囚心锁ツ
    2020-12-15 16:05

    Calling the Dispose method is not required but you can still call it if you need for some reasons.

    Proof: HttpClient and lifetime management

    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.

    Check the source of DefaultHttpClientFactory:

    public HttpClient CreateClient(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException(nameof(name));
        }
    
        var handler = CreateHandler(name);
        var client = new HttpClient(handler, disposeHandler: false);
    
        var options = _optionsMonitor.Get(name);
        for (var i = 0; i < options.HttpClientActions.Count; i++)
        {
            options.HttpClientActions[i](client);
        }
    
        return client;
    }
    

    The instance of HttpMessageHandler stores unmanaged resources of the HttpClient. In the classical scenario the HttpClient creates the instance of HttpMessageHandler and disposes it while itself disposing.

    You can see in the above code that different instances of HttpClient shares single instance of HttpMessageHandler and doesn't dispose it (disposeHandler: false).

    So, the call of the HttpClient.Dispose does nothing. But it's not dangerous.

提交回复
热议问题