WebClient非常慢

Hoo*_*och 11 .net c# networking webclient httpwebrequest

我有Webclient的问题.

这很慢.从一个网站下载串串大约需要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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

fox*_*oxy 29

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

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