views:

27

answers:

1

I have an ImageList that is populated with, well you guessed it, images. These images are loaded into memory in a dataset as a Bitmap. Until I loaded them into the ImageList the rise of memory is not worry. But when they are added to the ImageList the memory usage sky rockets. But the biggest problem is when I have to reload the list of images. I've tried to call dispose on every image on the list but the memory is not freed. This is the code I tried to clean up the memory:

        foreach (Image item in imageList.Images)
        {
            item.Dispose();

        }
        imageList.Images.Clear();

        GC.Collect();

What am I doing wrong?

+2  A: 

Your dispose code is not appropriate. Iterating the Images collection actually creates a new bitmap for each image. Which you then immediately dispose again. Just call Clear().

GC.Collect() cannot have any effect either, the ImageList class is a wrapper around the native Windows component. Which stores the images in native memory, not garbage collected memory.

Last but not least your real issue: the Windows memory manager just doesn't work the way you think. It does not shrink the virtual memory size of the program when it frees memory. It simply marks the block of memory as unused and adds it to the list of free blocks. Ready to be re-used at a later time. Only in the very rare case where the freed memory happens to span the entire set of reserved memory pages can it shrink the virtual memory size. This is not a real problem. It's virtual.

Hans Passant
The Dispose cycle and the GC.Colect call were made in a despair attempt to solve the problem because just calling Clear did not do the trick.
jpsstavares
The problem is that when I populate the list a second time, I get a Out of memory exception if the lists are too big. That's why I'm saying the memory is not freed.
jpsstavares
Are you disposing the bitmaps after you add them to the ImageList?
Hans Passant
I think I've tried that in the foreach cycle. I'm adding Bitmaps to the ImageList so imageList.Images gives me the Bitmaps I'm trying to dispose.
jpsstavares
No, you misunderstand. You have to dispose the bitmaps early, right after you added them to the ImageList. The native control makes a copy. You cannot dispose the bitmaps later, the reference is gone. If the bitmaps are very large then there's always good odds for OOM because memory is getting fragmented.
Hans Passant