VB.net 图片加载内存问题

工作中碰到一个内存泄漏问题。记录一下以备后用。

修改前代码:

    Private Function BitmapToBitmapSource(source As Bitmap) As BitmapSource
        Return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                         source.GetHbitmap(),
                         IntPtr.Zero,
                         Int32Rect.Empty,
                         BitmapSizeOptions.FromEmptyOptions())
    End Function


修改后

Declare Function DeleteObject Lib "gdi32.dll" (ByVal hObject As IntPtr) As Boolean
    Private Function BitmapToBitmapSource(source As Bitmap) As BitmapSource
        Dim sysIntr As System.IntPtr = source.GetHbitmap()
        Dim bitmapSource As BitmapSource
        bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                         sysIntr,
                         IntPtr.Zero,
                         Int32Rect.Empty,
                         BitmapSizeOptions.FromEmptyOptions())
        DeleteObject(sysIntr)
        Return bitmapSource
    End Function


问题的根本原因系统设计的不好,调用GetHbitmap后GDI模块分配的内存托管代码并不负责释放, 需要自己调用

DLL相应C++代码释放。



你可能感兴趣的:(WPF)