Why do I get an OutOfMemoryException when I have images in my ListBox?

Oh, I recently killed whole day to make this working!

So the solution is:

Make your Image control free resources. So set the

BitmapImage bitmapImage = image.Source as BitmapImage;
bitmapImage.UriSource = null;
image.Source = null;

as it was mentioned before.

Make sure you virtualize _bitmap on every item of the list. You should load it on demand (LongListSelector.Realized method) and you have to destroy it! It won’t going to collect automatically and GC.Collect doesn’t work either.
Null reference is not working too 🙁
But here is the method:
Make 1×1 pixel file. Copy it into assembly and make resource stream from it to dispose your images with 1×1 pixel blank. Bind custom dispose method to LongListSelector.UnRealized event (e.Container handles your list item).

public static void DisposeImage(BitmapImage image)
{
    Uri uri= new Uri("oneXone.png", UriKind.Relative);
    StreamResourceInfo sr=Application.GetResourceStream(uri);
    try
    {
        using (Stream stream=sr.Stream)
        {
            image.DecodePixelWidth=1; //This is essential!
            image.SetSource(stream);
        }
    }
    catch { }
}

Working for me in LongListSelector with 1000 images 400 width each.

If you miss the 2 step with the data collection you can see the the good results but the memory overflows after 100-200 items scrolled.

Leave a Comment