为什么图像不被GC处理?

本文关键字:处理 GC 图像 为什么 | 更新日期: 2023-09-27 18:02:47

我在c#中从OpenCV Emgu获得帧,我在一段时间后耗尽了内存。当我手动处理旧框架时,问题就消失了。这似乎只有在我从Emgu那里得到帧时才会发生。例如,如果我从AForge获得帧,它会像预期的那样被清理。

由于我在CopyToNewBPP中复制了数据并处理了捕获的帧,因此应该释放unmanaged中的内存。当我在图片框中设置一个新的位图时,不应该有对旧帧的引用。

问题是我的理解中缺少了什么

private void button1_Click(object sender, EventArgs e)
    {
        Capture capture = new Capture("rtsp://192.168.0.89:554/live2.sdp");
        Task t = new Task(() =>
        {
            DateTime last = DateTime.Now;
            while (true)
            {
                var frame = capture.QueryFrame();
                if (frame == null)
                {
                    continue;
                }
                Bitmap bitmap = CopyToNewBPP((Bitmap)frame.Bitmap);
                frame.Dispose();
                pictureBox1.Invoke(new MethodInvoker(() =>
                {
                    var old = pictureBox1.Image;
                    pictureBox1.Image = bitmap;
                    if (old != null)
                    {
                        old.Dispose(); // this should be done automatically by GC in my mind
                    }
                }));
                frame.Dispose();
            }
        });
        t.Start();
    }
    public Bitmap CopyToNewBPP(Bitmap orig, PixelFormat format = PixelFormat.Format32bppRgb)
    {
        Bitmap clone = new Bitmap(orig.Width, orig.Height, format);
        using (Graphics gr = Graphics.FromImage(clone))
        {
            gr.DrawImage(orig, new Rectangle(0, 0, clone.Width, clone.Height));
        }
        return clone;
    }

为什么图像不被GC处理?

我不知道我的答案是否有帮助

图像Gui程序是重要的内存点击。

e。g代码。

if(pictureBox.Image != null)
{
   pictureBox.Image.Dispose();
   pictureBox.Image = null;
   pictureBox.Image = [New Image];
}