2012-09-23 42 views
0

我試圖通過webclient下載文件,代碼如下所示。問題是,如果我連續404響應很長時間,我的服務器達到100%,查看事件日誌告訴發生堆棧溢出。這裏的「count」變量是爲了避免0個字節的文件,count440是爲404個響應。404響應遞歸webclient.download方法導致服務器達到100%

int count = 0; int count404 = 0; 
    public Stream DownloadFileThroughWebClient(string strFilePath) 
    { 
     try 
     { 
      if (count >= 120 || count404 >= 30) 
      { 
       count = 0; 
       count404 = 0; 
       return null; 
      } 
      System.Threading.Thread.Sleep(1000); 
      System.Net.WebClient wc = new System.Net.WebClient(); 
      var v = wc.DownloadData(strFilePath); 
      Stream FileToSave = new MemoryStream(v); 
      byte[] bytes = new byte[FileToSave.Length]; 
      int numBytesToRead = (int)FileToSave.Length; 
      if (numBytesToRead > 0) 
      { 
       count = 0; 
       count404 = 0; 
       return FileToSave; 
      } 
      else 
      { 
       count++; 
       count404 = 0; 
       return DownloadFileThroughWebClient(strFilePath); 
      } 
     } 
     catch (Exception ex) 
     { 
      count++; 
      count404++; 
      return DownloadFileThroughWebClient(strFilePath); 
     } 
    } 

在此先感謝。

+0

你應該換你的WebClient的'using'塊。 – Adam

+0

嗨@codesparkle感謝您的回覆..我認爲它是因爲遞歸異常,我的服務器在CPU上越來越高?你給了我新的想法。 – gaurav

+0

不處理WebClient不會像您所遇到的那樣導致堆棧溢出(這更可能是由遞歸引起的)。無論如何,這是一個好主意。爲了避免堆棧溢出,您可能需要實現* explicit *堆棧。谷歌「用迭代替換遞歸」。 – Adam

回答

1

試試這個(不使用遞歸和正確計數404):

public Stream DownloadFileThroughWebClient(string strFilePath) 
{ 
    int count = 0; 
    int count404 = 0; 

    while (count < 120 && count404 < 30) 
    { 
     try 
     { 
      byte[] v; 
      using (var wc = new WebClient()) 
      { 
       v = wc.DownloadData(strFilePath); 
      } 

      if (v.Length > 0) 
      { 
       return new MemoryStream(v); 
      } 

      count++; 
      count404 = 0; 
     } 
     catch (WebException ex) 
     { 
      count++; 
      var httpWebResponse = ex.Response as HttpWebResponse; 
      if (httpWebResponse != null && httpWebResponse.StatusCode == HttpStatusCode.NotFound) 
      { 
       count404++; 
       // you may wanna break out of the loop here since there's no point in continuing 
      } 
     } 
     catch (Exception ex) 
     { 

     } 
    } 
    return null; 
} 
1

您致電:

return DownloadFileThroughWebClient(strFilePath); 

,如果出錯了。如果它保持404(或更可能:ip-blocked用於濫用查詢),那麼當然是,那麼你將會使用stackoverflow。這就是發生的情況如果你多次遞歸調用自己。所以:不要這樣做。某種「while」循環(對於成功或持續失敗而言具有理智退出條件)似乎比遞歸更合適。

+0

謝謝馬克這是發生了什麼..你搖滾 – gaurav

相關問題