System.Net.WebClient 异常缓慢 [英] System.Net.WebClient unreasonably slow
问题描述
使用 系统时.Net.WebClient.DownloadData() 方法我的响应时间太慢了.
When using the System.Net.WebClient.DownloadData() method I'm getting an unreasonably slow response time.
在 .NET 中使用 WebClient 类获取 url 时,大约需要 10 秒才能得到响应,而浏览器在 1 秒内获取相同页面.这是针对 0.5kB 或更小的数据.
When fetching an url using the WebClient class in .NET it takes around 10 sec before I get a response, while the same page is fetched by my browser in under 1 sec. And this is with data that's 0.5kB or smaller in size.
请求涉及 POST/GET 参数和用户代理标头,如果这可能会导致问题.
The request involves POST/GET parameters and a user agent header if perhaps that could cause problems.
如果在 .NET 中下载数据的其他方法给我带来了同样的问题,我还没有(还)尝试过,但我怀疑我可能会得到类似的结果.(我一直觉得 .NET 中的网络请求异常缓慢...)
I haven't (yet) tried if other ways to download data in .NET gives me the same problems, but I'm suspecting I might get similar results. (I've always had a feeling web requests in .NET are unusually slow...)
这可能是什么原因?
我尝试使用 System.Net.HttpWebRequest
来做确切的事情,使用以下方法,所有请求都在 1 秒内完成.
I tried doing the exact thing using System.Net.HttpWebRequest
instead, using the following method, and all requests finish in under 1 sec.
public static string DownloadText(string url)
var request = (HttpWebRequest)WebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
虽然这个(旧)方法使用 System.Net.WebClient
需要 15-30 秒才能完成每个请求:
While this (old) method using System.Net.WebClient
takes 15-30s for each request to finish:
public static string DownloadText(string url)
{
var client = new WebClient();
byte[] data = client.DownloadData(url);
return client.Encoding.GetString(data);
}
推荐答案
我在使用 WebRequest 时遇到了这个问题.尝试设置 Proxy = null;
I had that problem with WebRequest. Try setting Proxy = null;
WebClient wc = new WebClient();
wc.Proxy = null;
默认情况下,WebClient、WebRequest 尝试从 IE 设置中确定要使用的代理,有时会导致实际请求发送前延迟 5 秒.
By default WebClient, WebRequest try to determine what proxy to use from IE settings, sometimes it results in like 5 sec delay before the actual request is sent.
这适用于所有使用 WebRequest 的类,包括具有 HTTP 绑定的 WCF 服务.通常,您可以在应用程序启动时使用此静态代码:
This applies to all classes that use WebRequest, including WCF services with HTTP binding. In general you can use this static code at application startup:
WebRequest.DefaultWebProxy = null;
这篇关于System.Net.WebClient 异常缓慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!