C# – Dispose of Image in WPF in Listbox (memory leak)

cmemory-managementwpf

I have a ListBox with a bunch of images in it (done through a datatemplate). The images are created by setting the items source:

<Image x:Name="ItemImage" Source="{Binding ImageUrl}"/> 

and then they are cleared by using the listbox's Items.Clear() method. New Images are added by using the Items.Add method of the listbox.

However, memory usage just starts moving up and up and up. It is the same 300 or so small images that are getting displayed, but the memory never seems to get freed. The App starts using about 40Megs, and quickly climbs up to 700Megs. How do I free up the memory that all these images are using?

EDIT: One thing I forgot to mention, the images (which are about 4-5k each in size) are being loaded over the network. Is caching somehow responsible for this? Displaying 12 Images chews up about 10 Megs of memory, which is about 100X filesize.

Best Answer

Unless you are doing anything unusual when loading the images (like using homebrewed image loaders or something) then the GC should wipe them out for you when nothing is referencing them anymore.

Are you holding on to references to the data anywhere? Remember that events and event handlers can sometimes "trick" the garbage collector into thinking that an object is still in use:

MyObject obj = new MyObject();
obj.TheEvent += new EventHandler(MyHandler);
obj = null;
// Now you might think that obj is set for collection but it 
// (probably - I don't have access to MS' .NET source code) isn't 
// since we're still listening to events from it.

Not sure if this applies to you, but at least that's were I'd check if I were you.

Also, if you have access to a profiler, such as AQTime or similar, then running your code through it might give you some hints.

You could also try and see if it makes any difference if you load images from disk or from resources embedded into your assembly.