我有这个在表单加载时调用的函数:
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;
}
在创建图像对象时,在foreach期间的某个时刻,该函数退出并且永远不会完成。我有什么特别的错误吗?
封闭使用中的所有内容似乎解决了问题,尽管它很慢:
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;
}
答案 0 :(得分:1)
在循环到新URI之前关闭MemoryStream,或使用using语句。