添加Interval时,HttpWebRequest会变慢

测试下载网页源的不同可能性我得到了以下结果(google.com,9gag.com的平均时间毫秒):

  • 普通的HttpWebRequest:169,360
  • Gzip HttpWebRequest:143,260
  • WebClient GetStream:132,295
  • WebClient DownloadString: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; } 

有什么想法来解决这个问题?

也许尝试一下,虽然它可能只能帮助您处理单个请求,并且在执行multithreading版本时实际上会使事情变得更糟。

 ServicePointManager.UseNagleAlgorithm = false; 

以下是来自HttpWebRequest类的 MSDN文档的引用

另一个可能对性能产生影响的选项是使用UseNagleAlgorithm属性。 当此属性设置为true时,TCP / IP将尝试使用TCP Nagle算法进行HTTP连接。 Nagle算法在发送TCP数据包时聚合数据。 它在通过网络发送数据之前将小消息序列累积到更大的TCP数据包中。 使用Nagle算法可以优化网络资源的使用,尽管在某些情况下性能也会降低。 通常,对于恒定的高容量吞吐量,使用Nagle算法实现性能改进。 但对于较小吞吐量的应用程序,可能会出现性能下降。

应用程序通常不需要更改设置为true的UseNagleAlgorithm属性的默认值。 但是,如果应用程序使用低延迟连接,则将此属性设置为false可能会有所帮助。

我认为您可能正在泄漏资源,因为您没有在每次方法调用时丢弃所有IDisposable对象。

提供此版本并尝试查看它是否为您提供更一致的执行时间。

 public string getWebsite( string Url ) { Stopwatch stopwatch = Stopwatch.StartNew(); HttpWebRequest http = (HttpWebRequest) WebRequest.Create( Url ); http.Headers.Add( HttpRequestHeader.AcceptEncoding, "gzip,deflate" ); string html = string.Empty; using ( HttpWebResponse webResponse = (HttpWebResponse) http.GetResponse() ) { using ( Stream responseStream = webResponse.GetResponseStream() ) { Stream decompressedStream = null; if ( webResponse.ContentEncoding.ToLower().Contains( "gzip" ) ) decompressedStream = new GZipStream( responseStream, CompressionMode.Decompress ); else if ( webResponse.ContentEncoding.ToLower().Contains( "deflate" ) ) decompressedStream = new DeflateStream( responseStream, CompressionMode.Decompress ); if ( decompressedStream != null ) { using ( StreamReader reader = new StreamReader( decompressedStream, Encoding.Default ) ) { html = reader.ReadToEnd(); } decompressedStream.Dispose(); } } } Debug.WriteLine( stopwatch.ElapsedMilliseconds ); return html; }