C#System.OutOfMemoryException未处理

Kay*_*ayX 1 c# out-of-memory

我使用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
        }
Run Code Online (Sandbox Code Playgroud)

但它出来了错误

System.OutOfMemoryException was unhandled
  Message=Out of memory.
  Source=System.Drawing 
Run Code Online (Sandbox Code Playgroud)

问题是由foreach循环引起的,在进程完成后保持循环吗?我应该怎样做才能释放记忆?谢谢.

Ree*_*sey 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.
    }
Run Code Online (Sandbox Code Playgroud)

请注意,不仅是图像可能是问题,而是任何实现的资源IDisposable.许多课程System.Drawing都是一次性的 - 确保你可以像上面那样访问它们(通过使用),或者Dispose()在完成后调用它们.