我正在使用图像进行预览。工作后,我只是将ImageSource设置为null并调用GC.Collect(),但是在调用GC.Collect()之后,仍有50%的内存处于保留状态,直到我再次调用GC.Collect()为止。
为什么需要我打扫电话?
单击后销毁
private void ImgDistry_Click(object sender, RoutedEventArgs e)
{
image.Source = null;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
销毁图像后,设置image.Source = null,然后调用GC.Collect();。内存仍处于保留状态。一段时间后应该自动清洁。
并且它会保留内存,直到15-30秒后我调用GC.Collect()2-3次。如何立即清除未使用的位图内存?
检查视频(内部代码和步骤):-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;
}
最佳答案
得到答案..将图像源设置为null后需要更新布局,然后调用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();
}