[英]Why .NET Core HttpWebRequest can't KeepAlive
HttpWebRequest
为每个请求创建一个新连接。 为什么不分享一个?
我已将 KeepAlive 选项设置为 true。
WIN7 .net core2.1 和.net core3.0
using System;
using System.Net;
using System.Threading;
namespace Question {
static void Test() {
var uri = new Uri("https://stackoverflow.com/");
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.KeepAlive = true;
using (var webResponse = (HttpWebResponse)webRequest.GetResponse()) {
// nothing
}
}
static void Main(string[] args) {
while (true) {
Test();
Thread.Sleep(1000);
}
}
}
Microsoft 希望每个人都使用 HttpClient,即使 HttpWebRequest 接口对于大多数简单情况来说更加直观。
他们只在 .NET Core 中实现了 HttpWebRequest,因为 .NET Standard 需要它。 而且他们没有费心做一个彻底的实现来使 KeepAlive 之类的东西正常工作。 .NET Core 中的 HttpWebReequest 是一个围绕 HttpClient 的瘦包装器,为每个调用创建一个新连接(这正是您不应该使用 HttpClient 的方式)。
这是一篇关于 Http 连接池如何在各种框架中工作的非常好的文章: https : //www.stevejgordon.co.uk/httpclient-connection-pooling-in-dotnet-core
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.