WPF CreateBitmapSourceFromHBitmap()的内存泄漏 [英] WPF CreateBitmapSourceFromHBitmap() memory leak

查看:2738
本文介绍了WPF CreateBitmapSourceFromHBitmap()的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过像素绘制图像像素内的WPF显示。我试图通过做这一个 System.Drawing.Bitmap 然后用 CreateBitmapSourceFromHBitmap()来创建一个<$ C C>的BitmapSource $的WPF图像控件。我有内存泄漏的地方,因为当 CreateBitmapSourceFromBitmap()反复调用的内存使用量上升,并且不落,直到应用程序结束。如果我不叫 CreateBitmapSourceFromBitmap()没有在内存使用量无明显变化。

I need to draw an image pixel by pixel and display it inside a WPF. I am attempting to do this by using a System.Drawing.Bitmap then using CreateBitmapSourceFromHBitmap() to create a BitmapSource for a WPF Image control. I have a memory leak somewhere because when the CreateBitmapSourceFromBitmap() is called repeatedly the memory usage goes up and does not drop off until the application is ended. If I don't call CreateBitmapSourceFromBitmap() there is no noticeable change in memory usage.

for (int i = 0; i < 100; i++)
{
    var bmp = new System.Drawing.Bitmap(1000, 1000);
    var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
        bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
    source = null;
    bmp.Dispose();
    bmp = null;
}

我能做些什么,以释放的BitmapSource 内存?

推荐答案

MSDN指出,对于 Bitmap.GetHbitmap()你是负责调用GDI DeleteObject方法释放所使用的GDI的位图对象的内存的所以使用下面的code:

MSDN states that for Bitmap.GetHbitmap(): You are responsible for calling the GDI DeleteObject method to free the memory used by the GDI bitmap object. So use the following code:

// at class level
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);

// your code
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1000, 1000)) 
{
    IntPtr hBitmap = bmp.GetHbitmap(); 

    try 
    {
        var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
    }
    finally 
    {
        DeleteObject(hBitmap)
    }
}

我也由一个使用语句替换你的的Dispose()电话。

I also replaced your Dispose() call by an using statement.

这篇关于WPF CreateBitmapSourceFromHBitmap()的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆