WebClient非常慢

我有Webclient的问题。

这很慢。 从一个网站下载String需要大约3-5秒。 我没有任何网络问题。

这是我的Modifed WebClient。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; namespace StatusChecker { class WebClientEx: WebClient { public CookieContainer CookieContainer { get; private set; } public WebClientEx() { CookieContainer = new CookieContainer(); ServicePointManager.Expect100Continue = false; Encoding = System.Text.Encoding.UTF8; WebRequest.DefaultWebProxy = null; Proxy = null; } public void ClearCookies() { CookieContainer = new CookieContainer(); } protected override WebRequest GetWebRequest(Uri address) { var request = base.GetWebRequest(address); if (request is HttpWebRequest) { (request as HttpWebRequest).CookieContainer = CookieContainer; } return request; } } } 

更新:在wireshark中,我看到单个DownladString正在发送和接收数千个数据包。

这里可能有两个问题(我之前在自己的程序中也注意到了这个问题):

  • 第一个请求需要非常长的时间 :这是因为默认情况下WebRequest会在第一次启动时检测并加载代理设置,这可能需要很长时间。 要停止此操作,只需将代理属性( WebRequest.Proxy )设置为null ,它将绕过检查(前提是您可以直接访问Internet)
  • 您不能一次下载超过2个项目 :默认情况下,您只能同时打开2个HTTP连接。 要更改此设置,请将ServicePointManager.DefaultConnectionLimit设置为更大的值。 我通常将其设置为int.MaxValue (只是确保您不会通过1,000,000个连接向主机发送垃圾邮件)。

也许它会对某人有所帮助。 某些Web服务支持压缩(gzip或其他)。 因此,您可以为请求添加Accept-Encoding标头,然后为Web客户端实例启用自动解压缩 。 Chrome以这种方式工作。

如果它与正在检查的初始代理设置相关,则有几个选项:

  1. 禁用Internet Explorer中的自动代理检测设置
  2. 将代理设置为null:

    WebClient.Proxy = null

  3. 在应用程序启动时,将默认webproxy设置为null:

    WebRequest.DefaultWebProxy = null;

在较旧的.NET代码中,而不是设置为null,您曾经写过这个(但现在首选null):

 webclient.Proxy = GlobalProxySelection.GetEmptyWebProxy();