Garbage collection fails to reclaim BitmapImage?

前端 未结 5 1404
被撕碎了的回忆
被撕碎了的回忆 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 06:04

    I am just telling my experience about reclaiming BitmapImage memory. I work with .Net Framework 4.5.
    I create simple WPF Application and Load a large image file. I tried to clear Image from memory using following code:

    private void ButtonImageRemove_Click(object sender, RoutedEventArgs e)
        {
    
            image1.Source = null;
            GC.Collect();
        }
    

    But It didn't work. I tried other solutions too , but I didn't get my answer. After a few days struggling, I found out if I press the button twice, GC will free the memory. then I simply write this code to call GC collector a few second after clicking the button .

    private void ButtonImageRemove_Click(object sender, RoutedEventArgs e)
        {
    
            image1.Source = null;
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate
            {
                System.Threading.Thread.Sleep(500);
                GC.Collect();
            }));
            thread.Start();
    
        }
    

    this code just tested in DotNetFr 4.5. maybe you have to freeze BitmapImage object for lower .Net Framework .
    Edit
    This Code doesn't work unless layout get updated. I mean if parent control get removed, GC fails to reclaim it.

提交回复
热议问题