所以我在这里有这个 foreach 循环
foreach (string file in condensedFilesList)
{
Image imgToAdd;
imgToAdd = Image.FromFile(file);
if (imgToAdd.Width < 1920 || imgToAdd.Height < 1080)
{
//neither of the commented out lines worked when placed here
//imgToAdd = null;
//imgToAdd.Dispose();
condensedFilesList.Remove(file);
}
else
{
//neither of the commented out lines worked when placed here
//imgToAdd = null;
//imgToAdd.Dispose();
continue;
}
}
它包含指向 .jpg 图像的文件路径列表。其中大约 80 个大小不一。我需要列表遍历每个图像,检查其分辨率是否为 1920*1080,如果不是,则从数组中删除该文件路径指针。
现在它正在经历,在 imgToAdd 变量中设置要查看的图像,然后如果 width 属性或 height 属性不匹配,则该项目将被删除。这适用于第一个条目。它的分辨率不符合要求,我的数组将从 80 个条目减少到 79 个条目。
但是我不能让我的 imgToAdd 变量清空,所以我可以为它分配一个新的文件路径。我一直遇到 OutOfMemoryException。我尝试运行 .Dispose(),将其设置为 null,但我无法让它真正清空其自身的资源。
在调试器中,.Dispose() 会导致 imgToAdd 在您检查元素时用一长串错误代替值。它的所有属性都在那里,但毫无值(value)并被错误所取代。如果我将它设置为 null,它将起作用,并且在下一次迭代中,imgToAdd = null。 Buuuuut,当它尝试为变量分配新的文件路径时,我仍然遇到 OutOfMemoryException。
所以我不知道这是怎么回事。我希望其他人可以指出我做错了什么,我看不到。
编辑2:
我只是要覆盖这个编辑空间,如果人们想在我更新时检查功能的演变,请点击编辑历史。我尝试使用 @dlatikay 推荐的 using(){} 语句,并将其写入新列表。但不幸的是,我仍然遇到 OutOfMemoryException。这里的功能是对的
var tempList = new List<string>();
foreach (string file in condensedFilesList)
{
using (Image imgToAdd = Image.FromFile(file))
{
if (imgToAdd.Width < 1920 || imgToAdd.Height < 1080)
{
continue;
}
else
{
tempList.Add(file);
}
}
}
condensedFilesList = tempList;
最佳答案
使用使用
。并将结果写入新列表,这样您就不会在枚举时修改源列表:
var finalList = new List<string>();
foreach (string file in condensedFilesList)
{
using(var imgToAdd = Image.FromFile(file))
{
if (imgToAdd.Width < 1920 || imgToAdd.Height < 1080)
{
/* omit */
}
else
{
finalList.Add(file);
}
}
}
无需分配 null,或显式调用 Dispose()。 我建议添加 try..catch,并非所有图像文件都有效。
关于c# - 无法让 .Dispose() 在 foreach 循环中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41048296/