WebClient is very slow
本文关键字:slow very is WebClient | 更新日期: 2023-09-27 18:04:56
我的Webclient有问题。
它非常慢。它需要大约3-5秒从一个网站下载字符串。我没有任何网络问题。
这是我修改过的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
,它将绕过检查(前提是您可以直接访问互联网) -
你不能一次下载超过2个项目:默认情况下,你只能同时打开2个HTTP连接。要改变这一点,将
ServicePointManager.DefaultConnectionLimit
设置为更大的值。我通常将此设置为int.MaxValue
(只需确保您不会使用1,000,000连接向主机发送垃圾邮件)。
如果它与被检查的初始代理设置相关,则有几个选项:
- 禁用Internet Explorer自动代理检测设置
-
设置代理为空:
WebClient。Proxy = null
-
在应用程序启动时设置默认webproxy为null:
WebRequest。
在旧的。net代码中,你可以这样写,而不是设置为null(但现在首选null):
webclient.Proxy = GlobalProxySelection.GetEmptyWebProxy();
也许它会帮助别人。一些web服务支持压缩(gzip或其他)。所以你可以为你的请求添加Accept-Encoding头,然后为web客户端实例启用自动解压缩。