【问题标题】:Why .NET Core HttpWebRequest can't KeepAlive为什么.NET Core HttpWebRequest 不能 KeepAlive
【发布时间】: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


【解决方案1】:

微软希望每个人都使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    相关资源
    最近更新 更多