使用外部引用代码时如何进行多线程处理 [英] How to do multithreading when using outside referenced code
问题描述
我设法使用 Aforge 运行网络摄像头.代码可以在我的回答中找到.
I managed to get a webcam running using Aforge. The code can be found in my answer here.
现在我想做一些计算机视觉的事情并将一些结果返回给主窗体.我遇到的线程问题来自该代码的这一部分:
Now I want to do some computer vision stuff and return back some results to the main form. The threading problem I have is in this part from that code:
void FinalVideo_NewFrame(object sender, NewFrameEventArgs eventArgs)
{ Bitmap video = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = video;
// count red colors
// not yet written
TextBox1.text = "demo error"; // >> i like to return a value to the main form
}
然而,问题是它正在另一个线程中处理视频帧,现在我无法将答案从该线程返回到主窗体.我没有写 Aforge,我只是链接了它并让它在我的表单上工作.
The problem however is it's doing the video frames in another thread, and now I can't return answers from that thread to the main form back. I didn't write the Aforge, I only linked it and made it work on my form.
我无法改变 Aforge 视频的工作方式.我的意思是它从来没有让我喜欢做的事情得到回报.有没有办法返回结果,比如文本框中的字符串文本.在运行此代码的主窗体上?
I can't change the way how Aforge video works. I mean it was never made to result something back that's something I like to do. Are there ways to get a result back, like a string text in a textbox. On the main form where this code runs from?
我能够遵循线程的示例代码,但这有点超出我的理解,因为我对 Aforge 中视频采集的设计方式没有太大影响.
I am able to follow a sample code of threading but this is a bit over my head since I got not much influence on how video acquisition in Aforge was designed.
我一直在想,为了更新文本框而引发另一个线程是否可行,但我不太确定,并想知道最终会创建多个线程,从而导致大量内核切换负载.
I have been wondering if raising another thread just to update a textbox might work but I am not that sure and wonder that in the end one would create to many threads, causing to much kernel switching load.
一些附加信息:上面的代码线程是从下面的这个按钮功能开始的.
Some additional info: the code thread above is started with this button function below.
private void button1_Click(object sender, EventArgs e)
{ FinalVideo = new VideoCaptureDevice(VideoCaptureDevices[comboBox1.SelectedIndex].MonikerString);
FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
FinalVideo.Start();
}
推荐答案
尝试像这样编写代码:
void FinalVideo_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap video = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Invoke((Action)(() =>
{
pictureBox1.Image = video;
TextBox1.text = "demo error";
}));
}
.Invoke
将 Action
委托的执行推送到创建 pictureBox1
控件的同一线程上,换句话说,UI线程.
The .Invoke
pushes the execution of the Action
delegate onto the same thread that created the pictureBox1
control, in order words, the UI thread.
这篇关于使用外部引用代码时如何进行多线程处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!