【问题标题】:Updating Multiple PictureBoxes from multiple threads从多个线程更新多个 PictureBox
【发布时间】:2014-03-15 16:23:19
【问题描述】:

我在主窗体上有两个图片框,一个是来自安装在机器人顶部的网络摄像头的视频流,另一个是一些用户反馈,它会不时更新,并附上它的想法图表它可以看到(命名地图)。两张图片都可以由任何线程更新。如何安全地更新这些图片?

目前我的主窗体有两个方法,其中有一个委托调用,如下所示:

public partial class MainForm : Form
{

public void videoImage(Image image)
{
    this.VideoViewer.Image = image;
    if (this.InvokeRequired)
    {
        this.Invoke(new MethodInvoker(delegate { videoImage(image); }));
     }
}

public void mapImage(Image image)
{
    this.VideoViewer.Image = image;
    if (this.InvokeRequired)
    {
        this.Invoke(new MethodInvoker(delegate { mapImage(image); }));
    }
}

}

机器人主线程中有这个:

public delegate void videoImageReady(System.Drawing.Image image);
public event videoImageReady videoImage;

第三个线程有

public delegate void mapImageReady(System.Drawing.Image image);
public event mapImageReady mapImage;

我不确定这是否是正确的方法,或者是否有更好的方法,这就是我找到的方法(但它不起作用)我找到了这个 example 和这个 @987654322 @,但我没有完全理解它们,所以我不完全确定如何实现它们。

提前致谢。

【问题讨论】:

  • 你使用的是System.Threading.Thread还是System.ComponentModel.BackgroundWorker
  • 很抱歉应该提到这一点。我正在使用 System.Threading.Thread

标签: c# multithreading user-interface thread-safety picturebox


【解决方案1】:

InvokeRequired 检查及其处理是为了确保 UI 控件在 UI 线程上更新,而不是从您自己的线程更新。您的代码看起来包含所有位,但您的代码顺序错误。我举一个例子:

// this is called from any thread
public void videoImage(Image image)
{
    // are we called from the UI thread?
    if (this.InvokeRequired)
    {
        // no, so call this method again but this
        // time use the UI thread!
        // the heavy-lifting for switching to the ui-thread
        // is done for you
        this.Invoke(new MethodInvoker(delegate { videoImage(image); }));
    } 
    else 
    {
        // we are now for sure on the UI thread
        // so update the image
        this.VideoViewer.Image = image;
    }
}

【讨论】:

    【解决方案2】:

    应该是:

    if (this.InvokeRequired)
    {
    this.Invoke(new MethodInvoker(delegate { videoImage(image); }));
    return;
    }
    

    否则,您将调用 MethodInvoker 委托,然后再调用普通委托。

    【讨论】:

      猜你喜欢
      • 2013-11-12
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      • 2017-10-07
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多