Image loading memory leak with C#

前端 未结 3 1787
梦谈多话
梦谈多话 2020-12-09 20:02

I have a memory leak issue in my application which loads a large amount of images. I\'m rather new to C#, and thought my days of memory leak issues were past. I can\'t figur

3条回答
  •  萌比男神i
    2020-12-09 20:39

    You need to call the GDI DeleteObject method on the IntPtr pointer returned from GetHBitmap(). The IntPtr returned from the method is a pointer to the copy of the object in memory. This must be manually freed using the following code:

    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    public static extern bool DeleteObject(IntPtr hObject);
    
    private static BitmapSource LoadImage(string path)
    {
    
        BitmapSource source;
        using (var bmp = new Bitmap(path))
        {
    
            IntPtr hbmp = bmp.GetHbitmap();
            source = Imaging.CreateBitmapSourceFromHBitmap(
                hbmp,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
    
            DeleteObject(hbmp);
    
        }
    
        return source;
    }
    

提交回复
热议问题