2017-01-05 27 views
-4

我有此功能被稱爲上形式負載:在foreach期間應用退出時碼(0)

public static List<Image> GetImages(List<string> file) 
    { 
     List<Image> imgSource = new List<Image>(); 
     var webClient = new WebClient(); 
     webClient.UseDefaultCredentials = true; 
     foreach (string uri in file) 
     { 
      if (uri.Contains("PublishingImages")) 
      { 
       byte[] imageBytes = webClient.DownloadData(uri); 
       MemoryStream ms = new MemoryStream(imageBytes); 
       Image returnImage = Image.FromStream(ms); 
       imgSource.Add(returnImage); 
      } 
     } 
     MessageBox.Show("Completed"); 
     return imgSource; 
    } 

在某一點而創建圖像對象函數退出並無法完成。有什麼具體的我在這裏做錯了嗎?

使用內附一切似乎解決這個問題,雖然它很慢:

public static List<Image> GetImages(List<string> file) 
{ 
    //file.RemoveRange(50, 50); 
    List<Image> imgSource = new List<Image>(); 
    //var webClient = new WebClient(); 

    using (WebClient webClient = new WebClient()) 
    { 
     webClient.UseDefaultCredentials = true; 
     foreach (string uri in file) 
     { 
      if (uri.Contains("PublishingImages")) 
      { 
       byte[] imageBytes = webClient.DownloadData(uri); 
       using (MemoryStream ms = new MemoryStream(imageBytes)) 
       { 
        Image returnImage = Image.FromStream(ms); 
        imgSource.Add(returnImage); 
       } 
      } 
     } 
    } 
    MessageBox.Show("Completed"); 
    return imgSource; 
} 
+3

使用異常處理和調試來確定原因。使用VS?設置一箇中斷點並逐行瀏覽每一行。 –

+1

-1因爲這個問題確實需要更加關注。我可以看到5行代碼,每個代碼都可能以不同的方式對問題產生影響。 –

回答

1

循環到新的URI之前,關閉的MemoryStream,或使用using語句。

+0

這不是OP的有用答案,而應該是更多的評論。 – Greg

+0

是的,我不允許對問題發表評論。我看到其他人在評論中提出了相同的意見。我可能會刪除這個,如果關閉流沒有幫助(這不會讓我感到驚訝)。 –

+0

這對我有用。謝謝。封閉所有使用。將更新我的問題以顯示答案。 – VinnyGuitara