c# picturebox memory releasing problem

前端 未结 3 1175
别那么骄傲
别那么骄傲 2020-12-17 17:50

I\'m a newby in C#. I have to repeatedly refresh a GUI picture box in a worker thread. The image is acquired from a camera polling a driver with a GetImage method that retri

相关标签:
3条回答
  • 2020-12-17 18:09

    The thing is, you're making a GDI bitmap of bmp with GetHbitmap, which according to msdn:

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

    Then the FromHbitmap method makes a copy of the GDI bitmap; so you can release the incoming GDI bitmap using the GDI DeleteObject method immediately after creating the new Image.

    So basically I would add:

    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    public static extern bool DeleteObject(IntPtr hObject);
    
    ...
    
    IntPtr gdiBitmap = bmp.GetHbitmap();
    
    // Release the copied GDI bitmap
    if (pic.Image != null)
    {
        pic.Image.Dispose();
    }
    
    pic.Image = System.Drawing.Image.FromHbitmap(gdiBitmap);
    
    // Release the current GDI bitmap
    DeleteObject(gdiBitmap);
    

    I am unsure if you need the GDI bitmap to perform some kind of transformation. In case you don't you can just assign the bitmap to the Image property of your PictureBox, and ignore the former solution:

    // Since we're not using unmanaged resources anymore, explicitly disposing 
    // the Image only results in more immediate garbage collection, there wouldn't 
    // actually be a memory leak if you forget to dispose.
    if (pic.Image != null)
    {
        pic.Image.Dispose();
    }
    
    pic.Image = bmp;
    
    0 讨论(0)
  • 2020-12-17 18:20

    There are several ways to release an image from pbox. I strongly recommend the way is that do not use pbox.Image = Image.FromFile.... If you do not use FileStream and you want to read it from file use BitMap class. Like this:

    Bitmap bmp = new Bitmap(fileName);
    pbox.Image = bmp; // notice that we used bitmap class to initialize pbox.
    

    ... and then you want to release the image file bmp.Dispose();
    Now you can delete, move or whatever you want to the file.

    0 讨论(0)
  • 2020-12-17 18:22

    Image implements IDisposable, so you should call Dispose on each Image instance that you create, when it is no longer needed. You could try to replace this line in your code:

    pic.Image = System.Drawing.Image.FromHbitmap(bmp.GetHbitmap());
    

    With this:

    if (pic.Image != null)
    {
        pic.Image.Dispose();
    }
    pic.Image = System.Drawing.Image.FromHbitmap(bmp.GetHbitmap());
    

    This will dispose the previous image (if any) before the new one is assigned.

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