Unmanaged Memory leak

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 05:13:35

问题


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


回答1:


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



回答2:


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



回答3:


The MSDN says You are responsible for calling the GDI DeleteObject method to free the memory used by the GDI bitmap object.. The following question deals with the same problem and there is already answer WPF CreateBitmapSourceFromHBitmap memory leak




回答4:


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.



来源:https://stackoverflow.com/questions/8670151/unmanaged-memory-leak

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!