简体   繁体   中英

Memory leak in C# winforms app on picturebox

my application reads frames from a video (does some processing) and then displays it in a picture box - this is done around 10 times a second and i have now ran into a problem where the picturebox image is not being disposed of correctly.

I get a memory leakage and eventually an out of memory exception.

   //Check if PictureBox already contains an image, if so dispose of it.
if (VideoDisplay.Image != null)
{
    VideoDisplay.Image.Dispose();
}
   //set parameter to the new image
displayImage = OverlayImage.UpdateImage(eventArgs.Frame, WarningText, WarningBrush);
   //set the picturebox to the new image
VideoDisplay.Image = displayImage;
   //dispose of brush & start garbage collector
WarningBrush.Dispose();
GC.Collect();

By commenting out the VideoDisplay.Image = displayImage line the memory leakage stops (but obviously i get no image).

Just wondered if anyone could give me a hand with this as i have never before worked with disposing of objects etc and dont know if i have made a mistake in disposing or have missed something out.

Found the answer turned out by removing the VideoDisplay.Dispose() it fixed it. By having a quick look up on this there may have been a lock put on the object which the GC cannot then collect.

Before you update image, you need to dispose it. I had similar problem.
Like so:

VideoDisplay.Image.Dispose();

After that line of code, update the image. For your scenario:

VideoDisplay.Image = displayImage;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM