Image loading memory leak with C#

前端 未结 3 1783
梦谈多话
梦谈多话 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条回答
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-09 20:39

    It seems that when you call GetHBitmap() you are responsible for freeing the object

    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    public static extern bool DeleteObject(IntPtr hObject);
    
    private void DoGetHbitmap() 
    {
        Bitmap bm = new Bitmap("Image.jpg");
        IntPtr hBitmap = bm.GetHbitmap();
    
        DeleteObject(hBitmap);
    }
    

    I'm guessing that the BitmapSource doesn't take responsibility for freeing this object.

    0 讨论(0)
  • 2020-12-09 20:52

    When you call

    bmp.GetHbitmap()
    

    a copy of the bitmap is created. You'll need to keep a reference to the pointer to that object and call

    DeleteObject(...)
    

    on it.

    From here:

    Remarks

    You are responsible for calling the GDI DeleteObject method to free the memory used by the GDI bitmap object.


    You may be able to save yourself the headache (and overhead) of copying the bitmap by using BitmapImage instead of BitmapSource. This allows you to load and create in one step.

    0 讨论(0)
提交回复
热议问题