最近有个C#项目要播放本地视频,想想还是用EmguCV较为方便,然后发现了EmguCV的内存管理问题,在播放视频的过程中,内存在一直增加,以为应该有个释放内存的函数啥的,但是在网上搜索半天没有找到结果。于是自己摸索着增加了个垃圾强制回收GC.Collect(),没想到问题就解决了,播放视频内存稳稳的,不再增长,应用到项目中一切正常。
大家有没有遇到这个问题呢?
以下是一段测试代码,大家可以试试看是不是这样
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);
}
}
}
}