检查WPF中的非法交叉线程调用
本文关键字:线程 调用 非法 WPF 检查 | 更新日期: 2023-09-27 17:58:58
我正在为Twitch编写Bot,我正在使用名为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中,您已经无法执行CheckForIllegalCrossThreadCall,所以有人能告诉我应该如何正确地执行此方法来解决此CrossThreadCall吗?
正确的方法是使用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;
});
}
或者,更好的是,使用数据绑定(如果可以的话),这样您就不必担心了。