【发布时间】:2015-10-14 22:02:59
【问题描述】:
我想在带有 WPF 的 Image 容器中显示 Bitmap。
private void updateImagePreview()
{
Bitmap bmp = new Bitmap(Screen.PrimaryScreen.WorkingArea.Width,
Screen.PrimaryScreen.WorkingArea.Height);
Graphics gr = Graphics.FromImage(bmp);
Image Image_Preview;
while (true)
{
gr.CopyFromScreen(0, 0, 0, 0, new System.Drawing.Size(bmp.Width, bmp.Height));
Image_Preview.Source = loadBitmap(bmp);
}
}
[DllImport("gdi32")]
static extern int DeleteObject(IntPtr o);
public BitmapSource loadBitmap(System.Drawing.Bitmap source)
{
IntPtr ip = source.GetHbitmap();
BitmapSource bs = null;
try
{
bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
ip, IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
finally
{
DeleteObject(ip);
}
return bs;
}
问题是,这会造成巨大的内存泄漏。泄漏发生在CreateBitmapSourceFromHBitmap 调用上,并在循环时填充内存,直到超过限制。如果我不使用那个调用,那么泄漏就会消失。知道为什么会这样吗?
【问题讨论】:
-
“内存泄漏”是什么意思?它应该被销毁后将引用保留在内存中吗?还是一个电话就能填满你的记忆?
-
它保留引用。一次调用就可以了,但内存泄漏仍然存在。
-
你看到this exact same question了吗?它有很多链接,但没有答案。
-
尝试另一种方法:将位图保存到 MemoryStream 并从该流中解码 BitmapImage 或 BitmapFrame(如 StackOverflow 上的多个帖子所示)
-
我尝试了here的方法,包括包装类,它也泄漏了内存。
标签: c# .net wpf memory-management memory-leaks