still memory-leaks in .net4 - binding memory BitmapImage to Image-Source

做~自己de王妃 提交于 2019-12-10 09:44:56

问题


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):

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


回答1:


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...



来源:https://stackoverflow.com/questions/9175755/still-memory-leaks-in-net4-binding-memory-bitmapimage-to-image-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!