C# 如何处置BitmapImage缓存?

C# 如何处置BitmapImage缓存?,c#,wpf,C#,Wpf,我面临内存泄漏问题。泄漏源于此: public static BitmapSource BitmapImageFromFile(string filepath) { BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; //here bi.CreateOptions = BitmapCreateOptions.IgnoreIma

我面临内存泄漏问题。泄漏源于此:

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
,其中包含一个
图像
,源代码是此函数的
位图图像

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

当我关闭
ScatterViewItem
时会出现问题,这反过来又会关闭
图像
。但是,缓存内存没有被清除。所以经过多次循环后,内存消耗相当大

卸载
函数期间,我尝试设置
image.Source=null
,但没有清除它

如何在卸载过程中正确清除内存?

我找到了答案。似乎这是WPF中的一个bug

我修改了函数以包括
冻结

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()
。否则,它仍将留在记忆中

这可能对你有用,谢谢,但遗憾的是GC没有收集到它。直接调用GC.Collect()也不会收集它。