本文介绍了不要HttpClient的和HttpClientHandler必须处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

和System.Net.Http.HttpClientHandler在.NET框架4.5实现IDisposable(通过System.Net.Http.HttpMessageInvoker).

使用语句文件说:

This answer uses this pattern:

var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("foo", "bar"),
        new KeyValuePair<string, string>("baz", "bazinga"),
    });
    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
    var result = client.PostAsync("/test", content).Result;
    result.EnsureSuccessStatusCode();
}

But the most visible examples from Microsoft don't call Dispose() either explicitly or implicitly. For instance:

In the announcement's comments, someone asked the Microsoft employee:

His answer was:

The second paragraph is superflous to this question, which is not concerned about how many times you can use an HttpClient instance, but if it necessary to dispose it after you no longer need it.

(Update: in fact that second paragraph is the key to the answer, as provided below by @DPeden.)

So my questions are:

  1. Is it necessary, given the current implementation (.NET Framework 4.5), to call Dispose() on HttpClient and HttpClientHandler instances? Clarification: by "necessary" I mean if there are any negative consequences for not disposing, such as resource leakage or data corruption risks.

  2. If it's not necessary, would it be a "good practice" anyway, since they implement IDisposable?

  3. If it's necessary (or recommended), is this code mentioned above implementing it safely (for .NET Framework 4.5)?

  4. If these classes don't require calling Dispose(), why were they implemented as IDisposable?

  5. If they require, or if it's a recommended practice, are the Microsoft examples misleading or unsafe?

解决方案

The general consensus is that you do not (should not) need to dispose of HttpClient.

Many people who are intimately involved in the way it works have stated this.

See Darrel Miller's blog post and a related SO post: HttpClient crawling results in memory leak for reference.

I'd also strongly suggest that you read the HttpClient chapter from Designing Evolvable Web APIs with ASP.NET for context on what is going on under the hood, particularly the "Lifecycle" section quoted here:

Or even open up DotPeek.

这篇关于不要HttpClient的和HttpClientHandler必须处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 20:07