0

I am writing my Bot for Twitch and i am using library called TwichLib (https://github.com/swiftyspiffy/TwitchLib) now in example which is made for WinForms there is method called globalChatMessageReceived and there is CheckForIllegalCrossThreadCalls = false;. So whole method looks like

        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;
        }

Now in WPF you are already unable to do this CheckForIllegalCrossThreadCalls so can someone point me on how should i properly do this method to solve this CrossThreadCalls?

HyperX
  • 1,121
  • 2
  • 22
  • 42

1 Answers1

2

The correct way to do this is to use the WPF dispatcher to perform the action on the UI thread:

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;
    });
}

Or, better, use data binding (if you can) so you don't need to worry about it.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • That looks interesting, by the way how its the correct way to use DataBinding in this case? Any examples to get known with databinding? – HyperX Jul 28 '16 at 08:26
  • 1
    @HyperX It's a pretty big subject... Try here: https://msdn.microsoft.com/en-us/library/ms750612(v=vs.110).aspx - you might want to just use BeginInvoke() for now... ;) – Matthew Watson Jul 28 '16 at 08:36
  • Hmm actualy its not working still i tried your method, when it receives msg in events there is still Exception, the calling thread cannot access this object because different thread owns it.. – HyperX Jul 28 '16 at 16:35
  • @HyperX Strange... Can you get the dispatcher using `this.Dispatcher` instead? – Matthew Watson Jul 29 '16 at 07:46