wpf 如何处理 BitmapImage 缓存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28364439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dispose BitmapImage cache?
提问by Darren Ng
I'm facing a memory leak issue. The leak comes from here:
我正面临内存泄漏问题。泄漏来自这里:
public static BitmapSource BitmapImageFromFile(string filepath)
{
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad; //here
bi.CreateOptions = BitmapCreateOptions.IgnoreImageCache; //and here
bi.UriSource = new Uri(filepath, UriKind.RelativeOrAbsolute);
bi.EndInit();
return bi;
}
I have a ScatterViewItem, which contains an Image, and the source is the BitmapImageof this function.
我有一个ScatterViewItem,其中包含一个Image,源是BitmapImage这个函数的 。
The actual thing is a lot more complex than this, so I can't simply put an Image into it. I also can't use the default load options, as the image file might be deleted and hence will face some permission issue accessing the file during deletion.
实际情况比这复杂得多,所以我不能简单地将图像放入其中。我也不能使用默认的加载选项,因为图像文件可能会被删除,因此在删除过程中访问文件会面临一些权限问题。
The problem occurs when I close the ScatterViewItem, which in turn closes the Image. However, the cached memory isnt cleared. So after many cycles, the memory consumption is pretty big.
当我ScatterViewItem关闭Image. 但是,缓存的内存不会被清除。所以经过多次循环,内存消耗相当大。
I tried setting image.Source=nullduring the Unloadedfunction, but it didn't clear it.
我image.Source=null在Unloaded功能中尝试设置,但没有清除它。
How do I clear the memory correctly during unloading?
如何在卸载过程中正确清除内存?
回答by Darren Ng
I found the answer here. Seems like it's a bug in WPF.
我在这里找到了答案。似乎这是 WPF 中的一个错误。
I modified the function to include Freeze:
我修改了函数以包括Freeze:
public static BitmapSource BitmapImageFromFile(string filepath)
{
var bi = new BitmapImage();
using (var fs = new FileStream(filepath, FileMode.Open))
{
bi.BeginInit();
bi.StreamSource = fs;
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.EndInit();
}
bi.Freeze(); //Important to freeze it, otherwise it will still have minor leaks
return bi;
}
I also create my own Close function, which will be called before I close the ScatterViewItem:
我还创建了自己的 Close 函数,该函数将在我关闭之前调用ScatterViewItem:
public void Close()
{
myImage.Source = null;
UpdateLayout();
GC.Collect();
}
Because myImageis hosted in a ScatterViewItem, GC.Collect()must be called before the parent is closed. Otherwise, it will still linger in memory.
因为myImage托管在 中ScatterViewItem,所以GC.Collect()必须在父级关闭之前调用。否则,它仍然会留在记忆中。

