2014-12-22 25 views
2

我想從URL下載一個字符串。不幸的是,它非常緩慢。WebClient下載字符串(幾個字符頁)是如此之慢

這裏是我的代碼:

// One of these types for two bad solutions anyway 
    // byte[] result = new byte[12]; 
    // string result; 
    using (var webClient = new System.Net.WebClient()) 
    { 
     String url = "http://bg2.cba.pl/realmIP.txt"; 
     //result = webClient.DownloadString(url); // slow as hell 
     //webClient.OpenRead(url).Read(result, 0, 12); // even slower 
    } 

大約需要4-5秒,這似乎非常不恰當的,我...這個網址的

內容是IP

XX.YYY.ZZ.FF 
+4

你有沒有使用Wireshark或類似的東西來看看在哪裏他的時間到了嗎? –

+0

我沒有使用WS cuz我不​​知道如何操作它 –

+0

@BartłomiejSobieszek讀入Wireshark然後 – Sybren

回答

4

固定的,對不起,這裏把這個問題我想,但...這裏是工作的代碼

string result; 
using (var webClient = new System.Net.WebClient()) 
{ 
    webClient.Proxy=null; 
    String url = "http://bg2.cba.pl/realmIP.txt"; 
    result = webClient.DownloadString(url); 
} 

只要設置代理服務器爲空的東西

+0

使用'GlobalProxySelection.GetEmptyWebProxy()'而不是null。閱讀我的答案以獲取更多詳細信息 – giammin

2

我試過你的代碼並添加了一些輸出。

 using (var webClient = new System.Net.WebClient()) 
     { 
      Stopwatch timer = Stopwatch.StartNew(); 
      String url = "http://bg2.cba.pl/realmIP.txt"; 
      timer.Stop(); 
      TimeSpan timespan = timer.Elapsed; 
      String tex1 = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds/10); 


      timer = Stopwatch.StartNew(); 
      String result = webClient.DownloadString(url); // slow as hell 
      timespan = timer.Elapsed; 
      String tex2 = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds/10); 


      timer = Stopwatch.StartNew(); 
      Stream stream = webClient.OpenRead(url); 
      timespan = timer.Elapsed; 
      String tex3 = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds/10); 

      timer = Stopwatch.StartNew(); 
      byte[] result2 = new byte[12]; 
      int val = webClient.OpenRead(url).Read(result2, 0, 12); // even slower 
      timespan = timer.Elapsed; 
      String tex4 = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds/10); 

      textBox1.Text = result; 
      t1.Text = tex1; 
      t2.Text = tex2; 
      t3.Text = tex3; 
      t4.Text = tex4; 
     } 

結果如下

enter image description here

你的代碼似乎是好的。 檢查你的防火牆和所有參與

2

這顯然是一個問題,你行/ PC /防火牆

您可以在線測試:

http://goo.gl/XRqLjn

大約需要500毫秒

enter image description here

更新自己的答案

後,如果您想使用沒有代理,你應該使用GetEmptyWebProxy()msdn如說:

webClient.Proxy=GlobalProxySelection.GetEmptyWebProxy(); 
+0

注意:即使'GlobalProxySelection.GetEmptyWebProxy()'已被棄用,這是我能夠加速WebClient請求的唯一方法。如果有人知道任何未被棄用的方式來實現相同的行爲,請讓我知道。 –