为什么 Console App 循环在 .NET Core 2.2.6 上有效,但在 .NET Framework 4.7.2 上无效

Why does Console App loop work on .NET Core 2.2.6 but not on .NET Framework 4.7.2

我有一个控制台应用程序,每隔几秒就会对一个网站执行 ping 操作。该循环在 .NET Core 上运行完美。但是,当我尝试 运行 .NET Framework 上的完全相同的代码时,它 运行 通过循环两次然后停止。我不明白为什么它会停止。两个 .NET 都安装了最新版本,但 .NET Framework 代码在第三次迭代时停止,并在 HttpWebResponse response = (HttpWebResponse)request.GetResponse();

处停止
while (!Console.KeyAvailable)
{
    try
    {
        Console.WriteLine("Pinging....");
        //WebRequest request = WebRequest.Create(args[1].ToString());
        WebRequest request = WebRequest.Create("https://www.google.com");
        request.Credentials = CredentialCache.DefaultCredentials;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if ((int)response.StatusCode == 200)
        {
            // success code here
        }
        else if ((int)response.StatusCode != 200)
        {
            // successful connection but not code 200
        }

        Console.WriteLine(response.StatusDescription);
        Console.Write((int)response.StatusCode + "\n");
    }
    catch (WebException webexcp)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("Exception Caught");
        Console.WriteLine("Site not found");
        WebExceptionStatus status = webexcp.Status;
    }

    System.Threading.Thread.Sleep(500);
}

问题是 .NET Framework 将控制台应用程序限制为每个域 two outgoing requests

因此,您需要在完成后增加 ServicePointManager.DefaultConnectionLimit 的值或(最好)增加 responseDispose 的值。

disposing,该请求不再计入两个限制。

那么为什么这没有影响 .NET Core?因为它默认允许 int.MaxValue,而不是 2 个并发连接。

我认为问题在于您没有处理 response 对象,因此您达到了允许的最大请求数。

您可以在 using 语句中处理它,例如:

Console.WriteLine("Pinging....");

WebRequest request = WebRequest.Create("https://www.google.com");
request.Credentials = CredentialCache.DefaultCredentials;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    Console.WriteLine($"Status: {(int)response.StatusCode} {response.StatusDescription}");
}

您可以改为使用 HttpClient class,它没有相同的限制(您没有 来处理的响应):

static readonly HttpClient client = new HttpClient();

private static void Main()
{
    while (!Console.KeyAvailable)
    {
        PingWebsite("http://www.google.com/");
        Thread.Sleep(500);
    }
}

private static async void PingWebsite(string site)
{
    Console.WriteLine("Pinging...");

    try
    {
        HttpResponseMessage response = await client.GetAsync(site);
        response.EnsureSuccessStatusCode();
        Console.WriteLine($"Status: {(int) response.StatusCode} {response.ReasonPhrase}");
    }
    catch (HttpRequestException e)
    {
        Console.WriteLine($"\nException Caught!\nMessage: {e.Message}");
    }
}