【发布时间】:2020-01-07 02:30:26
【问题描述】:
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);
}
}
}
【问题讨论】:
-
你为什么使用 HttpWebRequest 而不是 HttpClient?在任何情况下
KeepAlive并不意味着您请求的连接被池化和重用。 HttpClient 确实使用了一个可重用连接池。这就是为什么should be reused
标签: c# .net-core httpwebrequest keep-alive