gpt4 book ai didi

c# - 如何在WPF应用程序上修复 “The calling thread cannot access this object because a different thread owns it.”

转载 作者:行者123 更新时间:2023-12-03 13:21:27 34 4
gpt4 key购买 nike

我有以下WPF代码,它在“TextBox t = tabItem.Content as TextBox;”处给了我一个异常(exception)。错误显示“调用线程无法访问该对象,因为其他线程拥有它”。如何解决该异常?

问候!

private void btnAdd_Click(object sender, RoutedEventArgs e)
{
RichTextBox statusRichTextBox = new RichTextBox();
CloseableTabItem tabItem = new CloseableTabItem();
tabItem.Content = statusRichTextBox;
tabItem.Header = "New Tab";
MainTab.Items.Add(tabItem);
Thread t = new Thread(new ParameterizedThreadStart(worker));
t.Start(tabItem);
}


public void worker(object threadParam)
{
CloseableTabItem tabItem = (CloseableTabItem)threadParam;

TextBox t = tabItem.Content as TextBox; //exception here
if (t != null)
Window1.myWindow1.Dispatcher.BeginInvoke((Action)(() => { t.Text = "THIS IS THE TEXT"; }), System.Windows.Threading.DispatcherPriority.Normal);
}

最佳答案

UI对象的属性和方法只能在创建这些对象的线程上访问,因此,当您尝试在辅助线程上访问tabItem.Content时,它将失败。

您可以改为:

TextBox t;
Window1.myWindow1.Dispatcher.Invoke(new Action(() => t = tabItem.Content as TextBox));

关于c# - 如何在WPF应用程序上修复 “The calling thread cannot access this object because a different thread owns it.”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8114609/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com