c#系统.OutOfMemoryException未处理

本文关键字:未处理 OutOfMemoryException 系统 | 更新日期: 2023-09-27 18:14:50

我使用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循环在进程结束后继续循环引起的吗?我应该做些什么来释放记忆?谢谢。

c#系统.OutOfMemoryException未处理

鉴于您的异常,看起来您正在处理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()