最近在做一个多线程图像采集与检测程序的界面,由于要与相机、PLC、后端推理程序打交道,使用了多线程技术。由于对C#不熟,应用中产生了内存泄漏。记录下解决的过程。程序如下:
namespace WinFormsApp1
{
public partial class mainForm : Form
{
private Channel channel;
private CancellationTokenSource cts = new CancellationTokenSource();
private ConcurrentQueue<Mat> imageQueue = new ConcurrentQueue<Mat>();
private ConcurrentQueue<string> plcCommandQueue = new ConcurrentQueue<string>();
public mainForm()
{
InitializeComponent();
InitializeThreads();
}
private void InitializeThreads()
{
cts = new CancellationTokenSource();
// 启动相机采集线程
Task.Run(() => CameraCaptureLoop(cts.Token), cts.Token);
// 启动图像处理与推理线程(模拟)
Task.Run(() => ImageProcessingLoop(cts.Token), cts.Token);
// 可以在这里添加PLC通信线程,但这里仅模拟
// UI线程将定期从plcCommandQueue中读取命令并显示
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 1000; // 每秒检查一次PLC命令
timer.Tick += (sender, e) => UpdateUI();
timer.Start();
}
private void CameraCaptureLoop(CancellationToken token)
{


4793

被折叠的 条评论
为什么被折叠?



