如何配置BitmapImage缓存?
我正面临内存泄漏问题。 泄漏来自这里:
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; }
我有一个ScatterViewItem
,它包含一个Image
,源是这个函数的BitmapImage
。
实际上比这复杂得多,所以我不能简单地将一个Image放入其中。 我也无法使用默认的加载选项,因为图像文件可能会被删除,因此在删除过程中会遇到访问文件的一些权限问题。
当我关闭ScatterViewItem
时会出现问题,而ScatterViewItem
又关闭了Image
。 但是,缓存的内存未清除。 所以在经过多次循环后,内存消耗量非常大。
我尝试在Unloaded
函数期间设置image.Source=null
,但它没有清除它。
如何在卸载期间正确清除内存?
我在这里找到了答案。 好像它是WPF中的一个错误。
我修改了函数以包含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; }
我还创建了自己的Close函数,在关闭ScatterViewItem
之前将调用ScatterViewItem
:
public void Close() { myImage.Source = null; UpdateLayout(); GC.Collect(); }
由于myImage
托管在ScatterViewItem
,因此必须在关闭父级之前调用GC.Collect()
。 否则,它仍将留在内存中。
- nHibernate Validator自定义IMessageInterpolator
- 在Visual Studio中引用项目“readonly”?
- 从一行中精心设计多个对象
- 无法访问文件
- 如何使用StructureMap通过代码定义默认构造函数?
- 仅当使用NetworkService时,站点才会使用ApplicationPoolIdentity在本地启动:“HTTP错误503.服务不可用”。
- Xamarin表单:带圆角的StackLayout
- 当我将Webdriver Firefox配置文件设置为默认下载所有文件时它无法正常工作
- 清除cookie,会话和formsauth后,Asp.net在注销时删除服务器上的会话