Question

I know very similar questions were asked here in the past - but neither had a solution for my problem:

I load a image from memory into a BitmapImage:

    private static BitmapImage LoadImage(byte[] imageData)
    {
        if (imageData == null || imageData.Length == 0) return null;
        var image = new BitmapImage();
        using (var mem = new MemoryStream(imageData))
        {
            mem.Position = 0;
            image.BeginInit();
            image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = null;
            image.StreamSource = mem;
            image.EndInit();
        }
        image.Freeze();
        return image;
    }

And then use this (with INotifyPropertyChange) to bind the resulting BitmapImage to the Source of a Image object (on a Page).

Problem is: this will leak memory (a lot in my case up to 300MB on 2-3 images!)

You don't even find this using Profilers - only the .net Memory Profiler got me on track (as it's in unmanaged memory where all the bytes go - so ANTS tell me ".NET is using 19,24MB of 367,3MB total private bytes allocated to the application" - nice): Memory-Profiler output

enter image description here

No matter what I try - I don't get this leak away. Tried (single and all at once):

  • clear the Visual-Tree / remove the Image on Unload
  • Set the Image-Source to null
  • use ImageBrush in Rectangle instead of Image
  • other CacheOptions without Disposing the MemoryStream
  • don't Freeze the Image

I don't get this - really! As soon as I stop using the Image in the Source everything is ok (no leak).

Someone any options I can try?

REMARK Seems like this is no bug at all (see my second comment) - I have to check this so I will let the question open for now - maybe this can help with the other questions on this as well

Was it helpful?

Solution

Sorry guys - this was indeed no "BUG" but caused by high-resolution pictures.

Please comment on this if I should delete the question or if I should leave it here as other people might come into the same situation...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top