是否应该处理由 HttpClientFactory 创建的 HttpClient 实例? [英] Should HttpClient instances created by HttpClientFactory be disposed?
问题描述
因此,我在 Startup.cs 中使用服务集合注册了一个命名客户端:
So, I've registered a named client with the services collection in my Startup.cs:
services.AddHttpClient(someServiceName,
client => client.BaseAddress = baseAddress);
现在可以从我的服务提供商处注入一个 IHttpClientFactory
.
and now can inject an IHttpClientFactory
from my service provider.
使用这个 IHttpClientFactory
,我想出了一个客户端实例:
Using this IHttpClientFactory
, I conjure up a client instance:
var client = httpClientFactory.CreateClient(someServiceName)
曾几何时,在处理 HttpClient
实例时需要非常小心,因为它是 很少做正确的事情.
Once upon a time, it was necessary to be very careful about the disposing of HttpClient
instances, as it was rarely the right thing to do.
但是,现在我们有了HttpClientFactory
,这还重要吗?这个 client
是否应该/可以放心地处理?例如
However, now we have HttpClientFactory
, does this matter any more? Should/Can this client
be disposed without worry? e.g.
using (var httpClient = httpClientFactory.CreateClient(someServiceName))
using (var response = await httpClient.PostAsync(somePath, someData))
{
var content = await response.Content.ReadAsAsync<SomeResponse>();
//...
}
推荐答案
调用 Dispose
方法不是必需的,但如果出于某些原因,您仍然可以调用它.
Calling the Dispose
method is not required but you can still call it if you need for some reasons.
不需要处理客户端.Disposal 取消传出请求并保证在调用 Dispose 后不能使用给定的 HttpClient 实例.IHttpClientFactory 跟踪和处理 HttpClient 实例使用的资源.HttpClient 实例通常可以被视为不需要处理的 .NET 对象.
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.
检查 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;
}
HttpMessageHandler
的实例存储了 HttpClient
的非托管资源.在经典场景中,HttpClient
创建 HttpMessageHandler
的实例并在自己处理的同时处理它.
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.
在上面的代码中可以看到,HttpClient
的不同实例共享了HttpMessageHandler
的单个实例,并没有对其进行处理(disposeHandler:false
>).
You can see in the above code that different instances of HttpClient
shares single instance of HttpMessageHandler
and doesn't dispose it (disposeHandler: false
).
所以,HttpClient.Dispose
的调用什么都不做.但这并不危险.
So, the call of the HttpClient.Dispose
does nothing. But it's not dangerous.
这篇关于是否应该处理由 HttpClientFactory 创建的 HttpClient 实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!