网络更改后,带有 HttpClient 实例的 C# 客户端应用程序崩溃

C# client app with HttpClient instance crashed after network changed

我将 HttpClient 库与重用实例一起使用:我在 cunstructor 中创建实例,例如 m_HttpClient = new HttpClient();,然后在我的应用程序的整个生命周期中使用该实例。一切正常,直到使用此应用程序的用户更改网络(将以太网更改为 wifi 等 ....)。在此更改之后,与服务器的下一次通信导致应用程序崩溃(Windows 的事件系统中没有异常或日志消息)。当我处理 HttpClient 对象并重新创建它时,问题解决了,但是我失去了重用 HttpClient 对象的优势。

我在 netstandard 2.0 库中使用 HttpClient,它是从 netframework 4.7.2 调用的。应用

这是这个库的标准行为吗?还是我做的不好?

抱歉我的英语不好,谢谢。

Dot Net 设计指南说您应该使用 IHttpClientFactory 来实现弹性 HTTP 请求,而不是直接使用 IHttpClient。它将在内部拥有一个具有高效重用逻辑的实例池。

Also, use polly also for retrying (if needed) as changing the network will be a failure and in Another issue that developers run into is when using a shared instance of HttpClient in long-running processes. In a situation where the HttpClient is instantiated as a singleton or a static object, it fails to handle the DNS changes as described in this issue of the dotnet/runtime GitHub repository.

大部分信息来自微软文档,我在这个答案中挑选并引用了重要信息。您可以阅读此博客以获取信息。 link

Though this class implements IDisposable, declaring and instantiating it within a using statement is not preferred because when the HttpClient object gets disposed of, the underlying socket is not immediately released, which can lead to a socket exhaustion problem. For more information about this issue, see the blog post You're using HttpClient wrong and it's destabilizing your software.

Polly is a transient-fault-handling library that helps developers add resiliency to their applications, by using some pre-defined policies in a fluent and thread-safe manner.

使用 IHttpClientFactory 的好处

The current implementation of IHttpClientFactory, that also implements IHttpMessageHandlerFactory, offers the following benefits:

Provides a central location for naming and configuring logical HttpClient objects. For example, you may configure a client (Service Agent) that's pre-configured to access a specific microservice. Codify the concept of outgoing middleware via delegating handlers in HttpClient and implementing Polly-based middleware to take advantage of Polly's policies for resiliency. HttpClient already has the concept of delegating handlers that could be linked together for outgoing HTTP requests. You can register HTTP clients into the factory and you can use a Polly handler to use Polly policies for Retry, CircuitBreakers, and so on. Manage the lifetime of HttpMessageHandler to avoid the mentioned problems/issues that can occur when managing HttpClient lifetimes yourself.

我希望这可以帮助您找到适合您的答案。