正确处理 HttpclientHandler 的方法

Proper way of disposing HttpclientHandler

请问Handler的正确处理方式是什么?或者我真的需要处理它吗? 因为微软也在配置Handlerhttps://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler?view=netcore-3.1

这是我的静态处理程序。

  private static HttpClientHandler handlerWithProxy = new HttpClientHandler
        {
            UseCookies = false,
            UseDefaultCredentials = true,
            DefaultProxyCredentials = CredentialCache.DefaultCredentials,
            Proxy = new WebProxy($"{MyProxy.ProxyHost}:{MyProxy.ProxyPort}", false),
            UseProxy = true,
            SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls,
            ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }
        };

这里是我调用 dispose 的地方。正确吗?

     private static async Task<JsonDocument> ResponseMessage(HttpRequestMessage request, CancellationToken token)
    {
        HttpCompletionOption option = HttpCompletionOption.ResponseHeadersRead;

        using (HttpResponseMessage response = MyProxy.UseProxy ? await clientWithProxy.SendAsync(request, option, token).ConfigureAwait(false)
                                                       : await client.SendAsync(request, option, token).ConfigureAwait(false))
        {
            token.ThrowIfCancellationRequested();
            HttpStatusCode status = response.StatusCode;

            using (Stream stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
            {
                if (stream == null || stream.CanRead == false) { return default; }

                var options = new JsonDocumentOptions { AllowTrailingCommas = true };
                var json = await JsonDocument.ParseAsync(stream, options).ConfigureAwait(false);

                if (!response.IsSuccessStatusCode) { throw new InvalidDataException($"Error occured: {ParseError(uri, json, status)}"); }

                //is this right of calling the dispose if it is already null?
                if (handler == null) { handler.Dispose(); }

                return json;
            }
        }
    }

这个答案会很短,但很贴心:

处理程序在创建时绑定到 HttpClient。你不处理那些。只需用它创建您的 HttpClient 然后忘记它。微软网站上的那个例子不是典型的使用场景。

确保在创建 HttpClient 时将其设为静态并在 class 范围内:

private static readonly HttpClient clientWithProxy = new HttpClient(handlerWithProxy);

您应该在应用程序的整个生命周期内对所有 HTTP 请求重复使用相同的 HttpClient