gpt4 book ai didi

c# - .Net Core 3.1 HttpClient 不重用套接字

转载 作者:行者123 更新时间:2023-12-05 03:25:58 24 4
gpt4 key购买 nike

我有下面一段代码,我在 .Net 4.7.2 和 .Net Core 上运行,但我对每个框架都有不同的行为

public class Program
{


private HttpClient Client = new HttpClient();
public static async Task Main(string[] args)
{
Program example = new Program();

Console.WriteLine("Starting connections");
int numberofIterations = 10;
Task<HttpResponseMessage>[] awaitableTasks = new Task<HttpResponseMessage>[numberofIterations];
for (int i = 0; i < numberofIterations; i++)
{
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.RequestUri = new Uri("https://example.com");
httpRequestMessage.Method = new HttpMethod("GET");

awaitableTasks[i] = example.Client.SendAsync(httpRequestMessage);
//Console.WriteLine(result.StatusCode);
}

Console.WriteLine("Connections done");
await Task.WhenAll(awaitableTasks);

}
}

对于 .Net Core 框架,网络跟踪显示每个请求的单独 tcp 连接,而对于 .NEt 4.7.2 框架,套接字得到重用。

网络追踪 .Net Core

enter image description here

网络追踪 .Net 4.7.2

enter image description here

感谢您理解差异、解释此行为以及解决此问题的最佳方法的想法。

最佳答案

简短的回答,下面对代码的修改将强制我的 .net 核心应用程序不创建两个以上的套接字并重用它们。

     var socketsHandler = new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromSeconds(60),
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(20),
MaxConnectionsPerServer = 2
};

HttpClientHandler handler = new HttpClientHandler() { MaxConnectionsPerServer = 2 };

var Client = new HttpClient(handler);

更新的答案


更多详情:

.Net Framework 4.x.x HttpClient 实现建立在 HttpWebRequest 和 ServicePoint 之上,后者可由 ServicePointManager 管理。对于 ASP.NET 托管应用程序,ServicePointManager 的默认连接限制设置为 10,对于所有其他应用程序设置为 2,这就是为什么在我上面的示例中打开并重用 2 个套接字,因为应用程序被阻止创建超过 2 个连接(套接字) 每个服务点。

请参阅下面的引用资料以获得更多理解

https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.defaultconnectionlimit?view=net-6.0#system-net-servicepointmanager-defaultconnectionlimit

https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager?view=net-6.0

https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepoint?view=net-6.0

C# Does Each Instance of HttpClient Get it's Own ServicePoint

在 .Net Core 中,实现已多次更改,不再由 ServicePointManager 管理,并且没有默认连接限制。下面的文章包含 HttpClient 类的完整故事。

https://www.stevejgordon.co.uk/httpclient-connection-pooling-in-dotnet-core

感谢@user700390、@PanagiotisKanavos 和@JeremyLakeman 为获得此问题的答案提供的帮助和指导。

关于c# - .Net Core 3.1 HttpClient 不重用套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71849496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com