2017-04-12 64 views
0

我試圖在消息到達時從事件處理程序更新富文本框。由於某些原因,當所有消息到達時,富文本框只會在最後更新。從事件處理程序更新富文本框

代碼我使用:

private void OutputMessageToLogWindow(string message) 
    { 




     Application.Current.Dispatcher.BeginInvoke(new Action(() => 
     { 
      outputRichTxtBox.AppendText(message); 
      test.Text = message; 
     })); 
    } 
+0

嘗試過。一樣 –

回答

1

我覺得是你的代碼是不是線程安全的,併發的消息的情況下,有可能是某些消息將不通過執行以下更新在同一時間線:

outputRichTxtBox.AppendText(message); 
test.Text = message; 

因此,爲了使線程安全的,我會建議使用lockBeingInvoke方法內:

private static readonly object synchLock = new object(); 

private void OutputMessageToLogWindow(string message) 
{ 
    Application.Current.Dispatcher.BeginInvoke(new Action(() => 
    { 
     lock(synchLock) 
     { 
      outputRichTxtBox.AppendText(message); 
      test.Text = message; 
     } 
    })); 
}