【发布时间】:2012-07-06 21:48:21
【问题描述】:
测试下载网页源的不同可能性我得到了以下结果(以毫秒为单位的平均时间到 google.com,9gag.com):
- 普通 HttpWebRequest: 169, 360
- Gzip HttpWebRequest: 143, 260
- WebClient 获取流:132、295
- WebClient 下载字符串:143, 389
所以对于我的 9gag 客户端,我决定采用 gzip HttpWebRequest。问题是,在我的实际程序中实现后,请求花费了两倍以上的时间。
仅在两个请求之间添加 Thread.Sleep 时也会出现问题。
编辑:
只是稍微改进了代码,仍然是同样的问题:在循环中运行时,当我在请求之间添加延迟时,请求需要更长的时间
for(int i = 0; i < 100; i++)
{
getWebsite("http://9gag.com/");
}
每个请求大约需要 250 毫秒。
for(int i = 0; i < 100; i++)
{
getWebsite("http://9gag.com/");
Thread.Sleep(1000);
}
每个请求大约需要 610 毫秒。
private string getWebsite(string Url)
{
Stopwatch stopwatch = Stopwatch.StartNew();
HttpWebRequest http = (HttpWebRequest)WebRequest.Create(Url);
http.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
string html = string.Empty;
using (HttpWebResponse webResponse = (HttpWebResponse)http.GetResponse())
using (Stream responseStream = webResponse.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
html = reader.ReadToEnd();
}
Debug.WriteLine(stopwatch.ElapsedMilliseconds);
return html;
}
有解决这个问题的想法吗?
【问题讨论】:
-
以防万一您可以在循环函数中删除对 Debug.WriteLine 的调用?将 100 次迭代计时为一个块,并将总时间除以 100。应该大致相等。只是一个健全的检查,以确保 writeline 根本不会减慢你的速度。我很确定它应该很快,但确认一下也无妨。
标签: c# .net httpwebrequest gzip deflate