Image memory clean after i call GC.Collect() many

2019-04-14 17:24发布

问题:

I am using the image to preview. after my work, I just set ImageSource to null and call GC.Collect() but after call GC.Collect() 50% memory is still on hold and its hold up to when I call again GC.Collect() ..

why it takes my call to clean?.

After Click Destroy

private void ImgDistry_Click(object sender, RoutedEventArgs e)
    {
        image.Source = null;
        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
    }

After Destroy Image set image.Source = null, and call GC.Collect(); memory still on hold. it should be auto clean after some time.

and it holds memory until I call GC.Collect() 2-3 times after 15-30 seconds..how can i immediately clean unused bitmap memory?

Check Video(code and steps inside):- https://www.dropbox.com/s/457hhjnlttbzhlp/TinyTake%20by%20MangoApps-16-08-2018-06-28-51.mp4?dl=0

private void ImgDisplay_Click(object sender, RoutedEventArgs e)
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        var bitmap = new BitmapImage();
        using (var stream = File.OpenRead(filePath))
        {
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            bitmap.StreamSource = stream;
            bitmap.EndInit();
            bitmap.Freeze();
        }
        image.Source = bitmap;
    }

    private void ImgDistry_Click(object sender, RoutedEventArgs e)
    {
        image.Source = null;
        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
    }

    private void ImgSelect_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.ShowDialog();
        filePath = openFileDialog1.FileName;
    }

回答1:

Got the answer.. need to update layout after set null to image source then call GC

private void ImgDistry_Click(object sender, RoutedEventArgs e)
    {
        image.Source = null;
        UpdateLayout();
        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
    }