2017-03-16 65 views
0

這個問題已經回答了很多時間,但不幸的是,對我來說沒有答案正在工作。WebClient.DownloadString()很慢下載重複

我只是簡單地使用WebClient.DownloadString(),它的執行速度非常慢。我嘗試將WebClient.Proxy設置爲null和GlobalProxySelection.GetEmptyWebProxy(),它沒有工作,我也沒有接近最大化我的互聯網速度。我究竟做錯了什麼?

public partial class WebForm1 : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     var res = GetData("tp"); 
     ShowData(res); 
     res = GetData("nl"); 
     ShowData(res); 
     res = GetData("sp"); 
     ShowData(res); 
     res = GetData("en"); 
     ShowData(res); 
     res = GetData("in"); 
     ShowData(res); 
     res = GetData("st"); 
     ShowData(res); 
     res = GetData("sh"); 
     ShowData(res); 
     res = GetData("fl"); 
     ShowData(res); 
     res = GetData("ce"); 
     ShowData(res); 
    } 

    public IEnumerable<object> GetData(string playListName) 
    { 
     try 
     { 
      String url = string.Empty; 
      string jsonStr = string.Empty; 

      if (playListName == "tp") 
       url = "https://content.jwplatform.com/feeds/wDg7QXiZ.json"; 
      else if (playListName == "nl") 
       url = "https://content.jwplatform.com/feeds/ZluqvHh7.json"; 
      else if (playListName == "sp") 
       url = "https://content.jwplatform.com/feeds/CqjyIXVZ.json"; 
      else if (playListName == "en") 
       url = "https://content.jwplatform.com/feeds/FEvaC7IT.json"; 
      else if (playListName == "in") 
       url = "https://content.jwplatform.com/feeds/7HSiwnEm.json"; 
      else if (playListName == "st") 
       url = "https://content.jwplatform.com/feeds/ioE6BWAD.json"; 
      else if (playListName == "sh") 
       url = "https://content.jwplatform.com/feeds/XHZFlpw1.json"; 
      else if (playListName == "fl") 
       url = "https://content.jwplatform.com/feeds/N2gtCgnE.json"; 
      else if (playListName == "ce") 
       url = "https://content.jwplatform.com/feeds/Lw3otpHB.json"; 
      else 
       url = string.Empty; 

      using (var webClient = new WebClient()) 
      { 
       webClient.Proxy = null; // not working 
       //webClient.Proxy = GlobalProxySelection.GetEmptyWebProxy(); // not working 
       jsonStr = webClient.DownloadString(url); // take 8 to 10 seconds 
      } 
      return jsonStr; 
     } 
     catch (Exception) { return null; } 
    } 
} 

雖然調用瀏覽器上的網址是正常工作

+1

目前還不清楚代理方面與速度方面有什麼關係 - 或者您是否使用其他檢索數據的方式(例如瀏覽器)測試了速度。也許服務器很慢? –

回答

1

很難說什麼是緩慢的主要原因沒有深入研究它(看代碼的更廣泛的範圍,監測網絡和\或分析應用程序)。

說了這麼多,一般來講有幾件事我能想到的,可能會有幫助:

  1. 如果您可以使用HttpClient的多個呼叫,則它可能會提高性能。不像weblient獲得最佳性能,您需要重新使用相同的HttpClient實例(這可以爲您節省像dns查找之類的請求)。
  2. 如果您有很多請求並行運行,那麼您可能想知道.net允許您並行運行最多兩個請求。您可以通過配置端點的連接限制來更改它。

  3. 在情況下,它是可能的,你沒有這個配置還沒有,那麼你可以設置httpclienthandler automaticDecompression財產除外放氣或gzip的內容類型。這將使服務器在它支持它的情況下在將消息發送回你的頁面之前壓縮消息。

請記住,問題夜在其他地方 - 像網絡問題或端點限制。