更改图像时需要,从前一个图像释放内存

时间:2013-12-29 14:34:18

标签: c# wpf

下面是垃圾收集器仅删除每三个加载图像的代码,最后两个图像驻留在内存中。对于大型图像非常关键并且会定期导致“OutOfMemoryException”

private void map()
        {            
            GC.Collect();
            GC.WaitForPendingFinalizers();            
            byte[] buffer = System.IO.File.ReadAllBytes(path);
            MemoryStream ms = new MemoryStream(buffer); 
            BitmapImage bitmap33 = new BitmapImage();
            bitmap33.BeginInit();           
            bitmap33.StreamSource = ms;
            bitmap33.EndInit();
            bitmap33.Freeze();
            img.Source = bitmap33;  
        } 

1 个答案:

答案 0 :(得分:0)

您可以使用Process ExplorerPerfView等工具来查看您的流程是否对特定文件保留文件句柄,并确定代码的当前行为。

我建议使用using关键字。正如MSDN using statement reference所说,“文件是访问非托管资源的托管类型的示例...... using语句以正确的方式调用对象上的Dispose方法”。

希望我帮忙!