简体   繁体   English

为什么 .NET Core HttpWebRequest 不能 KeepAlive

[英]Why .NET Core HttpWebRequest can't KeepAlive

HttpWebRequest creates a new connection for each request. HttpWebRequest为每个请求创建一个新连接。 Why not share one?为什么不分享一个?

I've set the KeepAlive option to true.我已将 KeepAlive 选项设置为 true。

test enviroment测试环境

WIN7 .net core2.1 and .net core3.0 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 wants everyone to use HttpClient even though the HttpWebRequest interface is a lot more intuitive for most simple cases. Microsoft 希望每个人都使用 HttpClient,即使 HttpWebRequest 接口对于大多数简单情况来说更加直观。

They only implemented HttpWebRequest in .NET Core because .NET Standard requires it.他们只在 .NET Core 中实现了 HttpWebRequest,因为 .NET Standard 需要它。 And they didn't bother to do a thorough implementation to make things like KeepAlive work properly.而且他们没有费心做一个彻底的实现来使 KeepAlive 之类的东西正常工作。 The HttpWebReequest in .NET Core is a thin wrapper around HttpClient, creating a new connection for each call (which is exactly how you're NOT supposed to use HttpClient). .NET Core 中的 HttpWebReequest 是一个围绕 HttpClient 的瘦包装器,为每个调用创建一个新连接(这正是您不应该使用 HttpClient 的方式)。

Here is a very good article about how Http connection pooling works in the various frameworks: https://www.stevejgordon.co.uk/httpclient-connection-pooling-in-dotnet-core这是一篇关于 Http 连接池如何在各种框架中工作的非常好的文章: https : //www.stevejgordon.co.uk/httpclient-connection-pooling-in-dotnet-core

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM