How to dispose BitmapImage cache?

前端 未结 1 359
后悔当初
后悔当初 2020-12-18 03:02

I\'m facing a memory leak issue. The leak comes from here:

public static BitmapSource BitmapImageFromFile(string filepath)
{
    BitmapImage bi = new BitmapI         


        
相关标签:
1条回答
  • 2020-12-18 03:24

    I found the answer here. Seems like it's a bug in WPF.

    I modified the function to include 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:

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

    Because myImage is hosted in a ScatterViewItem, GC.Collect() must be called before the parent is closed. Otherwise, it will still linger in memory.

    0 讨论(0)
提交回复
热议问题