简体   繁体   English

HttpClient 完成后如何处理?

[英]How to dispose HttpClient after it's finished?

I want to use HttpClient to get content for my web page.我想使用HttpClient来获取我的 web 页面的内容。

public async Task<IActionResult> OnGet()
{
    NetworkCredential credentials = new NetworkCredential(Settings.Username, Settings.Password);

    using (HttpClientHandler handler = new HttpClientHandler { Credentials = credentials })
    using (HttpClient httpClient = new HttpClient(handler))
    {
        Content = await httpClient.GetStringAsync(requestUriString);
    }

    return Page();
}

The problem is that my using statements cause the HttpClient and HttpClientHandler objects to be destroyed before GetStringAsync() has completed.问题是我的using语句导致HttpClientHttpClientHandler对象在GetStringAsync()完成之前被销毁。

I can remove the using statements, but then I can't be assured the connections get disposed in a timely fashion.我可以删除using语句,但是我不能保证连接会及时处理。

Note that HttpClient does not implement IAsyncDisposable and so using await using is not an option.请注意, HttpClient没有实现IAsyncDisposable ,因此使用await using不是一个选项。

How can I ensure my HTTP objects get disposed of as soon as possible without disposing them before the code is finished?我怎样才能确保我的 HTTP 对象在代码完成之前被尽快处理掉?

So HttpClient is actually a bit weird in the context of being an IDisposable.所以 HttpClient 在作为 IDisposable 的上下文中实际上有点奇怪。 Even though it implements the IDisposable interface, Microsoft actually advises against placing it in a using statement .尽管它实现了 IDisposable 接口,但微软实际上建议不要将它放在 using 语句中

If you are using it in an ASP.NET Core context, you should use the HttpClientFactory to manage the lifetime of your HttpClients.如果你在 ASP.NET 核心上下文中使用它,你应该使用HttpClientFactory来管理你的 HttpClients 的生命周期。 If not, it is recommended to use a single static instance, but be wary that this can cause other issues, such as DNS staleness.如果不是,建议使用单个 static 实例,但要小心这可能会导致其他问题,例如 DNS 过时。

I found this article helpful when I had a similar issue: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ Here's an excerpt of the code you're looking for:当我遇到类似问题时,我发现这篇文章很有帮助: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/这是您要查找的代码的摘录:

private static HttpClient Client = new HttpClient();
public static async Task Main(string[] args) 
{
    Console.WriteLine("Starting connections");
    for(int i = 0; i<10; i++)
    {
        var result = await Client.GetAsync("http://aspnetmonsters.com");
        Console.WriteLine(result.StatusCode);
    }
    Console.WriteLine("Connections done");
    Console.ReadLine();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM