2012-02-07 60 views
1

WPF C#。我有一個綁定到不同方法的方法。 服務器發送一個hello world。WPF多線程。更改第三方流程的接口

var clientobj = 
(OperClass) Activator.GetObject 
(
typeof (OperClass), 
"tcp ://localhost: 100001/TcpClient" 
); 

clientobj.Update ("HELLO WORLD"); 

客戶端應用程序:

public void Update (string msg) 
{ 
    label1.text = msg;// error thread 
} 

中的程序被用於通信RemotingServices.Marshal。 如何將文本更改爲label1。 調度員沒有幫助。

+0

什麼錯誤,你得到什麼?當試圖設置'label1.Text'時它是一個跨線程錯誤嗎? – 2012-02-07 09:54:47

+0

是的,你是正確的這個錯誤。無法獲得控制流,因爲該項目未在其線程中創建。 – Feor 2012-02-07 10:01:56

回答

1

您不能從不是UI元素創建線程的線程訪問UI元素。爲了克服這個問題,你需要調用你創建UI元素的Dispatcher線程所需的東西。

假設clientobj這本身就是一個UI元素(如WindowUserControl),那麼你可以用下面的代碼:

public void Update (string msg) 
{ 
    // See if we need to re-invoke on the Dispatcher thread 
    if (!CheckAccess()) 
    { 
     // Invoke on the Dispatcher thread 
     this.Dispatcher.BeginInvoke(new Action<string>(Update), msg); 

     // Exit from this method to prevent continued execution 
     return; 
    } 

    // We are now running on the Dispatcher thread, so we can access the UI element(s) directly 
    label1.Text = msg; 
} 
+0

該計劃的工作。首先是包含在條件中的方法。然後重新調用一個方法來重命名UI。但該計劃沒有改變。也許你需要致電更新? – Feor 2012-02-07 10:44:30

+0

@Feor我不確定我明白你的意思。 – 2012-02-07 10:46:45

+0

您的代碼正常工作。但是在界面變化中沒有。雖然沒有錯誤。對不起我的英語不好。 – Feor 2012-02-07 10:50:21