非托管内存泄漏

afo*_*ard 7 c# memory wpf unmanaged bitmap

我正在使用一个使用BitmapSource的WPF应用程序,但我需要做一些操作,但我需要对System.Drawing.Bitmaps进行一些操作.

应用程序的内存使用在运行时会增加.

我已将内存泄漏范围缩小到此代码:

private BitmapSource BitmaptoBitmapsource(System.Drawing.Bitmap bitmap)
{
            BitmapSource bms;
            IntPtr hBitmap = bitmap.GetHbitmap();
            BitmapSizeOptions sizeOptions = BitmapSizeOptions.FromEmptyOptions();
            bms = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, sizeOptions);
            bms.Freeze();
            return bms;
}
Run Code Online (Sandbox Code Playgroud)

我认为这是非托管内存没有正确处理,但我似乎无法找到手动执行它.在此先感谢您的帮助!

亚历克斯

Mus*_*sis 9

你需要打电话DeleteObject(...)给你hBitmap.请参阅:http://msdn.microsoft.com/en-us/library/1dz311e4.aspx

private BitmapSource BitmaptoBitmapsource(System.Drawing.Bitmap bitmap)
{
    BitmapSource bms;
    IntPtr hBitmap = bitmap.GetHbitmap();
    BitmapSizeOptions sizeOptions = BitmapSizeOptions.FromEmptyOptions();
    bms = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, 
        IntPtr.Zero, Int32Rect.Empty, sizeOptions);
    bms.Freeze();

    // NEW:
    DeleteObject(hBitmap);

    return bms;
}
Run Code Online (Sandbox Code Playgroud)

  • 我准备写完全相同的答案;)这是`DeleteObject`方法的声明:`[DllImport("gdi32.dll")] static extern bool DeleteObject(IntPtr hObject);` (3认同)