Categories Tags

Objects Remaining in Memory

I was implementing an image resizer and I kept running into a problem where I kept getting error messages saying that the image file was in use even after I disposed of the object in memory (the last step was to remove the unresized image).

Calling object.Dispose() is just a suggestion to say “whenever you want, we don’t need this in memory anymore”. However, because it doesn’t get rid of it immediately, meaning that it is still being referenced which means that the file won’t be able to be deleted immediately.

In order to get around this, you need to call the garbage collector yourself to force the application to get rid of the object from memory.

The code:


string dest = @"C:\";
FileInfo imageFile = new FileInfo(file);
Image image = ResizeImage(Image.FromFile(file),size);
 
// Save the file to the file system
SaveAsJpeg(image, dest + imageFile.Name, 100);
 
// We don't need the image in memory any more (suggest it to be deleted)
image.Dispose();
 
// Call the garbage collector
GC.Collect();
GC.WaitForPendingFinalizers();
 
// Delete the old file
imageFile.Delete();

Posted in php

Tags: