I have a foreach loop where I do some operations with images. I was getting an OutOfMemoryException
when running this code with 50+ images; because the image instances are 15+ MB each.
var files = Directory.GetFiles(path).ToList();
foreach (var file in files)
{
Image image = new Bitmap(file);
//Do some operations
}
I removed the main logic because this problem still exists with this small piece of code. When I add GC.Collect();
in the foreach loop the problem is gone and I don't get an exception.
My question is: is the garbage collector too slow to clean up the images which aren't needed anymore without calling the Collect
method or am I missing something else?
Never noticed this problem before. I never thought there would be a problem because the //Do some operations
part needs ~1 second for each image. Should be enough time for the garbage collector I thought.