从另一个线程更新标签的最简单方法是什么?

我在thread1上运行了一个Form,然后我开始另一个线程(thread2)。当thread2处理一些文件时,我想用thread2工作的当前状态更新表单上的标签。

我怎么能这样做?


当前回答

WPF应用程序中最简单的方法是:

this.Dispatcher.Invoke((Action)(() =>
{
    // This refers to a form in a WPF application 
    val1 = textBox.Text; // Access the UI 
}));

其他回答

由于场景的平凡性,我实际上会让UI线程轮询状态。我想你会发现它可以很优雅。

public class MyForm : Form
{
  private volatile string m_Text = "";
  private System.Timers.Timer m_Timer;

  private MyForm()
  {
    m_Timer = new System.Timers.Timer();
    m_Timer.SynchronizingObject = this;
    m_Timer.Interval = 1000;
    m_Timer.Elapsed += (s, a) => { MyProgressLabel.Text = m_Text; };
    m_Timer.Start();
    var thread = new Thread(WorkerThread);
    thread.Start();
  }

  private void WorkerThread()
  {
    while (...)
    {
      // Periodically publish progress information.
      m_Text = "Still working...";
    }
  }
}

该方法避免了使用ISynchronizeInvoke.Invoke和ISynchroniizeInvoke.BeginInvoke方法时所需的封送处理操作。使用封送处理技术没有什么问题,但有几点需要注意。

请确保不要过于频繁地调用BeginInvoke,否则它可能会超出消息泵。在工作线程上调用Invoke是一个阻塞调用。它将暂时停止该线程中正在执行的工作。

我在这个答案中提出的策略颠倒了线程的通信角色。UI线程轮询数据,而不是工作线程推送数据。这是许多场景中使用的常见模式。由于您所要做的只是显示工作线程的进度信息,所以我认为您会发现此解决方案是编组解决方案的一个很好的替代方案。它具有以下优点。

UI和工作线程保持松散耦合,而不是Control.Invoke或Control.BeginVoke方法紧密耦合它们。UI线程不会阻碍工作线程的进度。工作线程不能支配UI线程更新的时间。UI和工作线程执行操作的间隔可以保持独立。工作线程不能超出UI线程的消息泵。UI线程可以决定何时以及多久更新一次UI。

前面回答中的Invoke内容都不是必需的。

您需要查看WindowsFormsSynchronizationContext:

// In the main thread
WindowsFormsSynchronizationContext mUiContext = new WindowsFormsSynchronizationContext();

...

// In some non-UI Thread

// Causes an update in the GUI thread.
mUiContext.Post(UpdateGUI, userData);

...

void UpdateGUI(object userData)
{
    // Update your GUI controls here
}

首先获取表单的实例(在本例中为mainForm),然后在另一个线程中使用此代码。

mainForm.Invoke(new MethodInvoker(delegate () 
{
    // Update things in my mainForm here
    mainForm.UpdateView();
}));

我刚读了答案,这似乎是一个非常热门的话题。我目前正在使用.NET 3.5 SP1和Windows窗体。

前面的答案中大量描述的使用InvokeRequired属性的著名公式涵盖了大多数情况,但不包括整个池。

如果尚未创建句柄怎么办?

InvokeRequired属性,如这里所述(Control.InvokeRequired属性对MSDN的引用),如果调用是从非GUI线程的线程进行的,则返回true;如果调用是由GUI线程进行的或尚未创建Handle,则返回false。

如果希望由另一个线程显示和更新模态表单,则可能会遇到异常。因为您希望以模态方式显示该表单,所以可以执行以下操作:

private MyForm _gui;

public void StartToDoThings()
{
    _gui = new MyForm();
    Thread thread = new Thread(SomeDelegate);
    thread.Start();
    _gui.ShowDialog();
}

代理可以更新GUI上的标签:

private void SomeDelegate()
{
    // Operations that can take a variable amount of time, even no time
    //... then you update the GUI
    if(_gui.InvokeRequired)
        _gui.Invoke((Action)delegate { _gui.Label1.Text = "Done!"; });
    else
        _gui.Label1.Text = "Done!";
}

如果标签更新之前的操作“花费的时间”(阅读并将其解释为简化)少于GUI线程创建表单句柄所花费的时间,则这可能会导致InvalidOperationException。这发生在ShowDialog()方法中。

您还应检查手柄,如下所示:

private void SomeDelegate()
{
    // Operations that can take a variable amount of time, even no time
    //... then you update the GUI
    if(_gui.IsHandleCreated)  //  <---- ADDED
        if(_gui.InvokeRequired)
            _gui.Invoke((Action)delegate { _gui.Label1.Text = "Done!"; });
        else
            _gui.Label1.Text = "Done!";
}

如果尚未创建handle,您可以处理要执行的操作:您可以忽略GUI更新(如上面的代码所示),也可以等待(风险更大)。这应该能回答这个问题。

可选材料:就我个人而言,我编写了以下代码:

public class ThreadSafeGuiCommand
{
  private const int SLEEPING_STEP = 100;
  private readonly int _totalTimeout;
  private int _timeout;

  public ThreadSafeGuiCommand(int totalTimeout)
  {
    _totalTimeout = totalTimeout;
  }

  public void Execute(Form form, Action guiCommand)
  {
    _timeout = _totalTimeout;
    while (!form.IsHandleCreated)
    {
      if (_timeout <= 0) return;

      Thread.Sleep(SLEEPING_STEP);
      _timeout -= SLEEPING_STEP;
    }

    if (form.InvokeRequired)
      form.Invoke(guiCommand);
    else
      guiCommand();
  }
}

我用这个ThreadSafeGuidCommand的一个实例为另一个线程更新的表单提供数据,并定义如下更新GUI(在我的表单中)的方法:

public void SetLabeTextTo(string value)
{
  _threadSafeGuiCommand.Execute(this, delegate { Label1.Text = value; });
}

通过这种方式,我很确定无论什么线程进行调用,我都会更新GUI,可以选择等待一段明确定义的时间(超时)。

还有另一个通用控件扩展。。

首先为Control类型的对象添加扩展方法

public static void InvokeIfRequired<T>(this T c, Action<T> action) where T : Control
{
    if (c.InvokeRequired)
    {
        c.Invoke(new Action(() => action(c)));
    }
    else
    {
        action(c);
    }
}

并从另一个线程调用类似的方法来访问UI线程中名为object1的控件:

object1.InvokeIfRequired(c => { c.Visible = true; });
object1.InvokeIfRequired(c => { c.Text = "ABC"; });

..或类似的

object1.InvokeIfRequired(c => 
  { 
      c.Text = "ABC";
      c.Visible = true; 
  }
);