2016-07-28 42 views
0

我正在寫我的Bot for Twitch,我現在使用庫稱爲TwichLib(https://github.com/swiftyspiffy/TwitchLib)現在在爲WinForms製作的示例中有方法globalChatMessageReceived並且有CheckForIllegalCrossThreadCalls = false;。所以整個方法看起來像CheckForIllegalCrossThreadCalls在WPF

 private void globalChatMessageReceived(object sender, TwitchChatClient.OnMessageReceivedArgs e) 
     { 
      //Don't do this in production 
      CheckForIllegalCrossThreadCalls = false; 

      richTextBox1.Text = String.Format("#{0} {1}[isSub: {2}]: {3}", e.ChatMessage.Channel, e.ChatMessage.DisplayName, e.ChatMessage.Subscriber, e.ChatMessage.Message) + 
       "\n" + richTextBox1.Text; 
     } 

現在在WPF你已經無法做到這一點CheckForIllegalCrossThreadCalls所以有人點我就應該怎麼正確做到這一點的方法來解決這個CrossThreadCalls?

+0

只是使用數據綁定,並忘記所有這些討厭的問題;) –

+0

可能重複[如何處理跨線程訪問異常?](http://stackoverflow.com/questions/11923865/how-to -deal-with-cross-thread-access-exceptions) –

+0

「CheckForIllegalCrossThreadCalls」是FORBIDDEN .....爲什麼大家還在用這個東西? – 2016-07-28 08:24:07

回答

2

正確的方式做,這是使用WPF調度執行UI線程上執行的操作:

private void globalChatMessageReceived(object sender, TwitchChatClient.OnMessageReceivedArgs e) 
{ 
    var dispatcher = Application.Current.MainWindow.Dispatcher; 
    // Or use this.Dispatcher if this method is in a window class. 

    dispatcher.BeginInvoke(new Action(() => 
    { 
     richTextBox1.Text = String.Format("#{0} {1}[isSub: {2}]: {3}", e.ChatMessage.Channel, e.ChatMessage.DisplayName, e.ChatMessage.Subscriber, e.ChatMessage.Message) + 
      "\n" + richTextBox1.Text; 
    }); 
} 

或者,更好,使用數據(如果你能)綁定,所以你不需要擔心它。

+0

看起來很有趣,順便說一句,在這種情況下,如何使用DataBinding的正確方法?任何通過數據綁定獲知的例子? – HyperX

+1

@HyperX這是一個相當大的主題...嘗試在這裏:https://msdn.microsoft.com/en-us/library/ms750612(v=vs.110).aspx - 你可能只想使用BeginInvoke()現在...;) –

+0

嗯實際上它不工作仍然我試過你的方法,當它收到事件仍有異常的情況下,調用線程無法訪問此對象,因爲不同的線程擁有它.. – HyperX