Garbage collection fails to reclaim BitmapImage?

前端 未结 5 1403
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 05:10

I have an application(WPF) which creates BitmapImages in huge numbers(like 25000). Seems like framework uses some internal logic so after creation there are approx 300 mb of

5条回答
  •  孤城傲影
    2020-12-11 05:58

    There was a bug in Wpf that we were bitten by where BitmapImage objects are not released unless you freeze them. http://blogs.msdn.com/b/jgoldb/archive/2008/02/04/finding-memory-leaks-in-wpf-based-applications.aspx was the original page where we discovered the issue. It should have been fixed in Wpf 3.5 sp1 but we were still seeing it in some situations. Try changing your code like this to see if that is the problem:

    bimages[i] = new BitmapImage(new Uri(paths[i % paths.Length]));
    bimages[i].Freeze();
    

    We routinely freeze our BitmapImage objects now as we were seeing other instances in the profiler where Wpf was listening for events on the BitmapImage and thereby keeping the image alive.

    If the Feeze() call isn't an obvious fix for your code, I would highly recommend using a profiler such as the RedGate Memory Profiler - that will trace a dependency tree that will show you what it is that is keeping your Image objects in memory.

提交回复
热议问题