我使用foreach来读取文件夹中的所有图像
string[] filePaths = Directory.GetFiles(Workspace.InputFolder, "*.*");
foreach (string imageFile in filePaths)
{
// Some Process here, the output are correct, just after output
the error happen
}
但它出来了错误
System.OutOfMemoryException was unhandled
Message=Out of memory.
Source=System.Drawing
foreach循环导致的问题是否在流程结束后继续循环? 我应该怎样做才能释放记忆? 感谢。
答案 0 :(得分:6)
鉴于您的异常,您似乎正在使用System.Drawing
命名空间中的对象。
例如,如果要在foreach循环中打开和操作图像,请确保在完成图像资源后立即调用Dispose()
来释放图像资源。或者,您可以将其包装在using
语句中,即:
foreach (string imageFile in filePaths)
{
using (var image = Image.FromFile(imageFile)
{
// Use the image...
} // Image will get disposed correctly here, now.
}
请注意,不仅是可能存在问题的图像,还有实现IDisposable
的任何资源。 System.Drawing
中的许多课程都是一次性的 - 请确保您按照上述方式(通过使用)访问它们,或者在完成时调用Dispose()
。