Search code examples
c#multithreadingbitmapdisposeemgucv

Disposing of Bitmaps used in background thread


I need to know how to properly dispose of Bitmaps so that I don't have a memory leak. I am grabbing video in a BackgroundWorker and assigning it to a PictureBox as such:

private void bwVideo_ReadCamera(object sender, DoWorkEventArgs e)
{
  Bitmap temp = null;
  while (true)
  {
    Image<Bgr, Byte> frame = logitec.QueryFrame();
    if (temp != null)
      temp.Dispose();
    temp = frame.ToBitmap();
    pictureBox2.Image = temp;
   }
}

The problem is that I still get a "Out of Memory Exception" with this code. I have tried freeing the pictureBox2.Image variable by using a BackgroundWorker ReportProgress and waiting in the above code for the dispose to finish (you need to be synched with the gui to call dispose on the PictureBox image). I have also tried to use the "Bitmap" property of the Image class which shares data between the Image and Bitmap.

So my questions is, in this situation, what is the proper way to dispose of my image?


Solution

  • You should probably have a using statement for your Image<Bgr, Byte> declaration. See the documentation.