WebClient是否使用KeepAlive?

时间:2011-01-15 10:07:50

标签: c# .net webclient keep-alive

我需要向单个主机发出大约50个HTTP请求(API调用)。性能很重要,所以我想使用HTTP KeepAlive。 WebClient是否支持此功能?

2 个答案:

答案 0 :(得分:19)

它在我的机器上,但我看不到它是记录的。我当然希望它默认。最简单的方法是运行Wireshark(或Fiddler)并查看确切的信息。

例如,这个程序:

using System;
using System.Net;

class Test
{    
    static void Main()
    {
        WebClient client = new WebClient();
        for (int i = 0; i < 50; i++)
        {
            string text = client.DownloadString("http://www.microsoft.com");
            Console.WriteLine(text.Length);
        }
    }
}

生成第一个请求:

GET / HTTP/1.1   
Host: www.microsoft.com    
Connection: Keep-Alive

子序列请求只是:

GET / HTTP/1.1
Host: www.microsoft.com

...大概是因为一旦连接处于KeepAlive模式,就会认为它会保持这种状态。

答案 1 :(得分:16)

如此处所述,WebClient在其私有实现http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx中使用了WebRequest。 Microsoft不会将其公开为您可以控制的公共财产。

因此,使用Reflector查看其实现,您可以看到如何为正在使用的WebRequest对象设置KeepAlive。就像@Jon指出的那样,实验表明KeepAlive设置为true。这也与其他场景相匹配,例如.NET remoting的私有实现。

在极少数情况下,您可能会发现KeepAlive = true会导致SocketException,然后您必须使用反射或其他技巧将其设置为false,这非常烦人。