AForge camera memory leak

后端 未结 3 887
遇见更好的自我
遇见更好的自我 2021-01-21 18:41

I\'m developing an application in C#, and I developed a library that does some stuff with Aforge cameras. One of the points is to simply capture images of what is i

相关标签:
3条回答
  • 2021-01-21 19:15

    AForge owns the bytes of the image, you should make your own deep copy. Passing the frame to the Bitmap constructor is not enough. If the framework is not able to properly dispose the bitmap because you have a reference to it, there's a leak.

    Try with this:

    private void NewFrame(object sender, NewFrameEventArgs args)
    {
        Bitmap newFrame = AForge.Imaging.Image.Clone(args.Frame);
        PictureBox.FromBitmapImage(newFrame);
        newFrame.Dispose();
    }
    
    0 讨论(0)
  • 2021-01-21 19:17

    This works for me.

            if (pictureBox1.Image != null) {
                pictureBox1.Image.Dispose();
            }
            Bitmap bitmap = eventArgs.Frame.Clone() as Bitmap;
            pictureBox1.Image = bitmap;
    
    0 讨论(0)
  • 2021-01-21 19:28

    Disposing picture box image right before assigning new one worked to prevent memory leak, but threw errors when I resized the picture box. Probably the problem is due to disposing the image too soon. What it worked for me was to keep old images in a queue, and dispose them with a delay of 5 images. This will give the picture box enough time to catch up.

    private Queue<Image> _oldImages = new Queue<Image>();
    ...
    
    if (pictureBox1.Image != null)
    {
      _oldImages.Enqueue(pictureBox1.Image);
      if (_oldImages.Count > 5) 
      {
        var oldest = _oldImages.Dequeue();
        oldest.Dispose();
      }
    }
    
    0 讨论(0)
提交回复
热议问题