【问题标题】:Unmanaged Memory leak非托管内存泄漏
【发布时间】:2012-01-30 00:09:38
【问题描述】:

我正在使用一个使用 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;
}

我认为这是未正确处理的非托管内存,但我似乎无法找到手动执行此操作的方法。提前感谢您的帮助!

亚历克斯

【问题讨论】:

标签: c# wpf memory bitmap unmanaged


【解决方案1】:

您需要在您的hBitmap 上致电DeleteObject(...)。见: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;
}

【讨论】:

  • 我正要写完全相同的答案;)这是DeleteObject方法的声明:[DllImport("gdi32.dll")] static extern bool DeleteObject(IntPtr hObject);
  • @ken2k:我正要添加完全相同的声明。谢谢!
【解决方案2】:

您需要在 hBitmap 上调用DeleteObject(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】:
    【解决方案4】:

    你要释放位图句柄吗?

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

    您负责调用 GDI DeleteObject 方法来释放 GDI 位图对象使用的内存。有关 GDI 位图的详细信息,请参阅 Windows GDI 文档中的位图。

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2011-02-20
      相关资源
      最近更新 更多