相关疑难解决方法(0)

是否必须处理HttpClient和HttpClientHandler?

.NET Framework 4.5中的System.Net.Http.HttpClientSystem.Net.Http.HttpClientHandler实现了IDisposable(通过System.Net.Http.HttpMessageInvoker).

using声明文件说:

通常,当您使用IDisposable对象时,您应该在using语句中声明并实例化它.

这个答案使用了这种模式:

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();
}
Run Code Online (Sandbox Code Playgroud)

但是微软最明显的例子并没有Dispose()明确地或隐含地调用.例如:

c# idisposable using .net-4.5 dotnet-httpclient

315
推荐指数
7
解决办法
12万
查看次数

标签 统计

.net-4.5 ×1

c# ×1

dotnet-httpclient ×1

idisposable ×1

using ×1