gpt4 book ai didi

c# - 如何配置BitmapImage缓存?

转载 作者:太空狗 更新时间:2023-10-29 21:33:26 24 4
gpt4 key购买 nike

我正面临内存泄漏问题。泄漏来自这里:

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

实际情况比这复杂得多,所以我不能简单地把一个图像放进去。我也不能使用默认的加载选项,因为图像文件可能会被删除,因此在删除过程中访问文件时会遇到一些权限问题。

问题发生在我关闭 ScatterViewItem 时,它又关闭了 Image。但是,缓存的内存不会被清除。所以经过多次循环后,内存消耗相当大。

我尝试在 Unloaded 函数中设置 image.Source=null,但它没有清除它。

卸载时如何正确清空内存?

最佳答案

我找到了答案 here .这似乎是 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 之前调用:

public void Close()
{
myImage.Source = null;
UpdateLayout();
GC.Collect();
}

因为 myImage 托管在 ScatterViewItem 中,所以必须在父级关闭之前调用 GC.Collect()。否则,它仍然会在内存中挥之不去。

关于c# - 如何配置BitmapImage缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28364439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com