WinForm与WPF下跨线程调用控件

Winform下:

public delegate void UpadataTextCallBack(string str,TextBox text);
public void UpadtaText(string str, TextBox text)
{
  if (text.InvokeRequired)
  {
    UpadataTextCallBack upadataTextCallBack = UpadtaText;
    text.Invoke(upadataTextCallBack, new object[] {str, text});
  }
  else
  {
    text.Text = str;
  }
}

  

然而在WPF下,并不支持Control.InvokeRequired。需要调用Dispatcher.Invoke()方法。

在 WPF 中,只有创建 DispatcherObject 的线程才能访问该对象。例如,一个从主 UI 线程派生的后台线程不能更新在该 UI 线程上创建的 Button的内容。为了使该后台线程能够访问 Button 的 Content 属性,该后台线程必须将此工作委托给与该 UI 线程关联的 Dispatcher。它使用Invoke 或BeginInvoke完成。Invoke是同步,BeginInvoke 是异步。该操作将按指定的 DispatcherPriority 添加到 Dispatcher 的事件队列中。

代码实例:

public delegate void UpadataTextCallBack(string str,TextBox text);

public void UpadtaText(string str, TextBox text)
{
     if (!Dispatcher.CheckAccess())
        {
          Dispatcher.Invoke(DispatcherPriority.Send, new setListTextCallBack(UpadtaText),str,text);
           return;
        } 
  text.Text = str; }

  

原文地址:https://www.cnblogs.com/dranched/p/5019662.html