System.Net.WebClient不合理地慢

moe*_*evi 40 .net c# performance http

使用System.Net.WebClient.DownloadData()方法时,我的响应时间非常慢.

在.NET中使用WebClient类获取URL时,在获得响应之前大约需要10秒,而我的浏览器在1秒内获取同一页面.这是因为数据大小为0.5kB或更小.

请求涉及POST/GET参数和用户代理标头(如果可能导致问题).

我还没有尝试过在.NET中下载数据的其他方法给我带来同样的问题,但我怀疑我可能得到类似的结果.(我一直觉得.NET中的Web请求非常慢......)

可能是什么原因造成的?

编辑:
我尝试System.Net.HttpWebRequest使用以下方法完成相应的操作,并且所有请求都在1秒内完成.

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();
        }
}
Run Code Online (Sandbox Code Playgroud)


虽然这个(旧)方法使用System.Net.WebClient每个请求完成需要15-30秒:

public static string DownloadText(string url)
{
       var client = new WebClient();
       byte[] data = client.DownloadData(url);
       return client.Encoding.GetString(data);
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*sev 80

我有WebRequest的问题.尝试设置Proxy = null;

    WebClient wc = new WebClient();
    wc.Proxy = null;
Run Code Online (Sandbox Code Playgroud)

默认情况下,WebClient,WebRequest尝试确定从IE设置中使用的代理,有时在发送实际请求之前会导致5秒延迟.

这适用于所有使用WebRequest的类,包括具有HTTP绑定的WCF服务.通常,您可以在应用程序启动时使用此静态代码:

WebRequest.DefaultWebProxy = null;
Run Code Online (Sandbox Code Playgroud)

  • 当我这样做时,我获得了巨大的*速度提升.谢谢! (2认同)

Har*_*wok 2

在这里下载 Wireshark http://www.wireshark.org/

捕获网络数据包并过滤“http”数据包。它应该立即给你答案。