简体   繁体   中英

Unmanaged Memory leak

I have am using a WPF application which uses BitmapSource but I need to do some manipulation but I need to do some manipulation of System.Drawing.Bitmaps.

The memory use of the application increases while it runs.

I have narrowed down the memory leak to this code:

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;
}

I assume it is the unmanaged memory not being disposed of properly, but I cannot seem to find anyway of doing it manually. Thanks in advance for any help!

Alex

You need to call DeleteObject(...) on your hBitmap . See: 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;
}

You need to call DeleteObject(hBitmap) on the hBitmap:

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

Are you releasing bitmap handle?

According to MSDN ( http://msdn.microsoft.com/en-us/library/1dz311e4.aspx )

You are responsible for calling the GDI DeleteObject method to free the memory used by the GDI bitmap object. For more information about GDI bitmaps, see Bitmaps in the Windows GDI documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM