Solve the memory growth problem when C#+EmguCV plays video

        Recently, there is a C# project that wants to play local video. It is more convenient to use EmguCV, and then I found the memory management problem of EmguCV. During the process of playing the video, the memory keeps increasing. I thought there should be a function to release the memory. But searching the Internet for a long time did not find any results. So I fumbled and added a garbage collection GC.Collect(), but I didn't expect the problem to be solved. The memory of the video playback is stable and no longer grows. Everything is normal when it is applied to the project.

      Have you encountered this problem?

      The following is a piece of test code, you can try it out

using Emgu.CV;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApp4
{
    public partial class Form1 : Form
    {
        Emgu.CV.VideoCapture vc=null;
        Bitmap bitmap;
        int fps = 25;

        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 打开文件开始播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "视频文件(*.mp4;*.avi)|*.MP4;*.avi";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (vc != null && vc.IsOpened)
                    vc.Dispose();
                vc = new Emgu.CV.VideoCapture(openFileDialog.FileName);
                fps = (int)vc.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.Fps);
                Thread thread = new Thread(VideoPlayThread);
                thread.Start();
            }
        }

        /// <summary>
        /// 播放线程
        /// </summary>
        private void VideoPlayThread()
        {
            Stopwatch sw = new Stopwatch();
            while (true)
            {
                sw.Restart();
                Mat mat  = vc.QueryFrame();
                this.Invoke((Action)delegate
                {
                    pictureBox1.Image = mat.Bitmap;
                });
                GC.Collect(); //强制进行垃圾回收
                sw.Stop();
                long time = 1000 / fps - sw.ElapsedMilliseconds;
                if (time > 0)
                    Thread.Sleep((int)time);
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/whf227/article/details/120740328