简体   繁体   中英

C# System.OutOfMemoryException was unhandled

i use foreach to read all the image from a folder

        string[] filePaths = Directory.GetFiles(Workspace.InputFolder, "*.*");
        foreach (string imageFile in filePaths)
        {
            // Some Process here, the output are correct, just after output 
               the error happen
        }

But it come out error

System.OutOfMemoryException was unhandled
  Message=Out of memory.
  Source=System.Drawing 

Is the problem cause by the foreach loop keep looping after the process finish? What should i do for releasing the memory? Thanks.

Given your exception, it looks like you're working with objects in the System.Drawing namespace.

If you are opening and manipulating an image in your foreach loop, for example, make sure that you call Dispose() to release the images resources as soon as you're done with them. You can, alternatively, wrap this in a using statement, ie:

    foreach (string imageFile in filePaths)
    {
        using (var image = Image.FromFile(imageFile)
        {
            // Use the image...
        } // Image will get disposed correctly here, now.
    }

Be aware that it's not just images that are potentially the problem, but any resource that implements IDisposable . Many of the classes in System.Drawing are disposable - make sure that you either access them as above (via using) or call Dispose() on them when done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM