2011-06-07 136 views
2

這是我的C#代碼。WebClient查詢需要很長時間才能完成,爲什麼?

WebClient client = new WebClient(); 

while (true) { 
    html = client.DownloadString("http://google.com"); 
    Console.WriteLine(string.Format("\tSize: {0}", html.Length)); 
} 

大約需要9秒鐘才能得到第一個結果。然後每個需要大約3秒鐘。

當我用Java來完成時,它需要不到1秒的時間。

你爲什麼覺得C#這麼慢?我該如何改進它?

+2

您的網絡有問題。這在我的機器上需要0.16秒:System.Net.WebClient client = new System.Net.WebClient(); var sw = System.Diagnostics.Stopwatch.StartNew(); string html = client.DownloadString(「http://google.com」); Console.WriteLine(string.Format(「Size:{0}」,html.Length)); Console.WriteLine(「Elapsed:」+ sw.Elapsed); – Marek 2011-06-07 08:00:39

+0

谷歌會扼殺你的請求。 – jgauffin 2011-06-07 08:01:26

+0

@jgauffin:爲什麼? – Stefan 2011-06-07 08:02:34

回答

-2

您的網絡可能有問題(如Mark評論)。

0

我注意到,第一個請求總是需要很長的時間使用WebClient或WebRequest ... 我做了一個與我構建的Socket-Http類相同的請求,它沒有時間。

但是在第一次請求後,它應該更快,更好。

找到了解決的問題

嘗試明確設置代理服務器。如果您沒有定義代理,則HttpRequest類將花時間搜索一個代理。一旦它(或沒有)找到它,它將在應用程序的整個生命週期中使用這些信息,加速後續的請求。

設置request.Proxy = null;

相關問題