如果我在注册为 Transient 的服务中使用 Flurl,我是否可以避免线程池 starvation/socket 问题?

Am I safe from thread pool starvation/socket issues if I use Flurl in a service thats registered as Transient?

假设我有一个在 Startup 中注册为 Transient 的简单服务,我这样使用 Flurl:

public async Task DoStuff()
    {
        string url = "some valid Url";
        await url
            .AppendPathSegment("notifications")
            .WithHeader("a header", headervalue1)
            .WithHeader("another header", headervalue2)
            .PostJsonAsync(data);
    }

这项服务将在我们的应用程序中大量使用。我能否指望 Flurl 有效地处理请求,以便我的应用程序不会在重负载下耗尽可用的套接字数量?

根据their docs: yes - the default usage, as you are showing, makes uses of the implementation guidelines provided by Microsoft

引用:

Flurl.Http is built on top of the System.Net.Http stack. If you're familiar with HttpClient, you probably already know this advice:

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Especially in server applications, creating a new HttpClient instance for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.

Flurl.Http adheres to this guidance by default. Fluent methods like this will create an HttpClient lazily, cache it, and reuse it for every call to the same host*:

来源:

https://flurl.dev/docs/client-lifetime/

https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-6.0#remarks


不过请记住 - “重负载”仍然意味着您会达到某些限制,例如:

  • 达到最大服务器连接数 - 即:可能的服务器过载
  • 达到最大客户端套接字使用率 - 即:启动太多并发连接

有关详细信息,请参阅: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.maxconnectionsperserver?view=net-6.0

这意味着您仍然需要对预期的连接数量进行健全性检查。