我正在编写我的Bot for Twitch并且我正在使用名为TwichLib(https://github.com/swiftyspiffy/TwitchLib)的库现在在为WinForms制作的示例中有一个名为globalChatMessageReceived
的方法,并且有CheckForIllegalCrossThreadCalls = false;
。所以整个方法看起来像
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 :(得分: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;
});
}
或者,更好的是,使用数据绑定(如果可以的话),这样您就不用担心了。