I'm suffering from an OutOfMemoryException when obtaining an Image from an ImageList I've been unable to find an appropriate solution to the problem.
I've got a Custom ListView control, which has attached to it an Event for the drawing of ListViewItems. This then calls a static method which is designed to draw the item.
For a ListView of around 300 items, we're getting the memory jump up around 100Mb each time the ListView is scrolled. The offending code has been tracked down to the following:
Image image = item.ImageList.Images[item.ImageKey];
if (image != null)
{
Size imageOffset = new Size((bounds.Width - image.Width) / 2, 2);
Point imagePosition = bounds.Location + imageOffset;
graphics.DrawImageUnscaled(image, imagePosition);
}
It seems (certainly on WinXP) that the garbage collection isn't working correctly, causing the memory to spiral. We've tried adding an image.Dispose() directly after the block of code to fix the issue, but that doesn't have any effect.
The only solution I have managed to find so far, is at the end of the static method to call GC.Collect(). The problem with this however is that it then causes the ListView to re-paint itself slowly and you end up getting artifacts on the screen while it attempts to re-draw.
Has anyone else experienced this? Or knows of a workaround?