【发布时间】:2015-08-21 15:34:11
【问题描述】:
我正在实现一个小型图像查看器,不幸的是我正面临内存泄漏。 以下是我的加载程序。
public BitmapSource getImage(string fileName, double width, double height)
{
FileStream s = File.Open(fileName, FileMode.Open);
Image i = Image.FromStream(s, false, false);
double iWidth = i.Width;
double iHeight = i.Height;
i.Dispose();
s.Close();
BitmapImage tmpImage = new BitmapImage();
tmpImage.BeginInit();
tmpImage.CacheOption = BitmapCacheOption.OnLoad;
tmpImage.UriSource = new Uri(fileName);
if (iWidth > iHeight)
{
tmpImage.DecodePixelWidth = (int)width;
}
else
{
tmpImage.DecodePixelHeight = (int)height;
}
tmpImage.EndInit();
return tmpImage;
}
这就是我调用加载器的方式
private void whenArrowKeyPressed(int index)
{
CurrentImage = fh.getImage(fileList[index], 1920, 1080);
}
CurrentImage 是一个属性,它绑定到 WPF ViewBox。
有什么想法吗? 我也尝试从 StreamSource 读取,效果相同。
【问题讨论】:
-
您没有处理 FileStream。调用 s.Dispose() 而不是 s.Close(); Dispose 也会处理关闭。
-
谢谢,我可以看到一些改进。不幸的是,它并没有完全解决问题。显示第一张图像时,应用程序使用 ca. 150MB,经过多次切换,我现在看到加到 ca,300MB
-
我认为您的问题一定出在您尚未发布的某些代码中。我在您发布的代码中没有发现任何其他错误。
-
顺便说一句,您可能想阅读以下内容:stackoverflow.com/questions/9175755/…。
-
谢谢。我也会检查剩余的代码。
标签: c# image memory-leaks bitmapimage