[英]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.