Garbage collection fails to reclaim BitmapImage?

前端 未结 5 1371
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 05:10

I have an application(WPF) which creates BitmapImages in huge numbers(like 25000). Seems like framework uses some internal logic so after creation there are approx 300 mb of

5条回答
  •  北海茫月
    2020-12-11 05:44

    What worked for me was to:

    1. Set the Image control's ImageSource to null
    2. Run UpdateLayout() before removing the control that contains the Image from the UI.
    3. Make sure that you Freeze() the BitmapImage when you create it and that there were no non-weak references made to the BitmapImage objects used as ImageSources.

    My cleanup method for each Image ended up being as simple as this:

    img.Source = null;
    UpdateLayout();
    

    I was able to arrive at this through experimentation by keeping a list with a WeakReference() object pointing at every BitmapImage that I created and then checking the IsAlive field on the WeakReferences after they were supposed to be cleaned up in order to confirm that they'd actually been cleaned up.

    So, my BitmapImage creation method looks like this:

    var bi = new BitmapImage();
    using (var fs = new FileStream(pic, FileMode.Open))
    {
        bi.BeginInit();
        bi.CacheOption = BitmapCacheOption.OnLoad;
        bi.StreamSource = fs;
        bi.EndInit();
    }
    bi.Freeze();
    weakreflist.Add(new WeakReference(bi));
    return bi;
    

提交回复
热议问题