经过大量研究后,我向您寻求帮助,因为我不知道该怎么办了。我正在使用 AForge VideoCaptureDevice 在图片框中显示相机。然而,内存消耗相当高,垃圾收集器出于某种原因不想释放内存。我创建了简单的测试应用程序,其中包含两个表单(Form1 和 Form2)。 Form1 只是通过单击按钮打开 Form2。 Form2 包含图片框,其中包含当前帧。 Form2 还包含用于停止 VideoCaptureDevice 并处理图像 + 关闭表单的按钮。当我通过 Form1 打开 Form2,然后单击按钮停止 VideoCaptureDevice 并关闭表单,我一遍又一遍地执行此操作时,内存不断增长(例如增长到 3GB),并且 GC 不会释放它 - 有时会释放它。
问题是,在我的真实应用程序中,当发生这种情况时,内存会增长到~1.1GB,然后 VideoCaptureDevice 停止触发 NewFrame 处理程序,直到我调用 GC.Collect() 来清理内存。
我尝试了所有方法,但无法解决问题。
namespace AForgeTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var form2 = new Form2();
form2.ShowDialog();
}
}
}
namespace AForgeTest
{
public partial class Form2 : Form
{
private FilterInfoCollection _filterInfoCollection;
private VideoCaptureDevice _videoCaptureDevice;
public Form2()
{
_videoCaptureDevice = new VideoCaptureDevice();//new VideoCaptureDevice();
_videoCaptureDevice.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);
_videoCaptureDevice.VideoSourceError += new VideoSourceErrorEventHandler(ErrorHandler);
_filterInfoCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
InitializeComponent();
}
private void ErrorHandler(object sender, VideoSourceErrorEventArgs eventArgs)
{
Console.WriteLine("Video feed source error: " + eventArgs.Description);
}
private void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
var bitmap = pictureBox1.Image;
pictureBox1.Image = new Bitmap(eventArgs.Frame);
bitmap?.Dispose();
}
private void Form2_Load(object sender, EventArgs e)
{
_videoCaptureDevice.Source = _filterInfoCollection[0].MonikerString;
_videoCaptureDevice.Start();
}
private void button1_Click(object sender, EventArgs e)
{
StopVideoCapture();
this.Close();
}
public void StopVideoCapture()
{
while (_videoCaptureDevice.IsRunning)
{
_videoCaptureDevice.SignalToStop();
_videoCaptureDevice.WaitForStop();
}
_videoCaptureDevice.NewFrame -= new NewFrameEventHandler(FinalFrame_NewFrame);
_videoCaptureDevice.VideoSourceError -= new VideoSourceErrorEventHandler(ErrorHandler);
_videoCaptureDevice = null;
var bitmap = pictureBox1.Image;
pictureBox1.Image = null;
bitmap?.Dispose();
}
}
}