简体   繁体   English

如何修复“调用线程无法访问此对象,因为不同的线程拥有它。”在WPF应用程序上

[英]How to fix “The calling thread cannot access this object because a different thread owns it.” on a WPF app

I have the following WPF code and it gives me an exception at "TextBox t = tabItem.Content as TextBox;" 我有以下WPF代码,它在“ TextBox t = tabItem.Content as TextBox;”处给了我一个例外。 the error says "The calling thread cannot access this object because a different thread owns it." 错误说“调用线程无法访问此对象,因为另一个线程拥有它。” How can I fix the exception? 我该如何修复异常?

Regards! 问候!

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

Properties and methods of UI objects can only be accessed on the thread that created these objects, so when you try to access tabItem.Content on a worker thread, it fails. UI对象的属性和方法只能在创建这些对象的线程上访问,因此当您尝试访问工作线程上的tabItem.Content时,它会失败。

You can do that instead: 您可以改为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 WPF Dispatcher {“调用线程无法访问此对象,因为其他线程拥有它。”} - WPF Dispatcher {"The calling thread cannot access this object because a different thread owns it."} 调用线程无法访问该对象,因为其他线程拥有它。 WPF关闭所有窗口 - The calling thread cannot access this object because a different thread owns it. WPF closing all windows WPF:调用线程无法访问此对象,因为其他线程拥有它 - WPF: The calling thread cannot access this object because a different thread owns it 抛出“调用线程无法访问此对象,因为另一个线程拥有它。” - Throws “The calling thread cannot access this object because a different thread owns it.” “调用线程无法访问该对象,因为其他线程拥有它。” c# - “The calling thread cannot access this object because a different thread owns it.” c# 调用线程无法访问此对象,因为其他线程拥有它。 例外 - The calling Thread cannot access this object because a different thread owns it. Exception 调用线程无法访问该对象,因为其他线程拥有它。 即使使用调度程序 - The calling thread cannot access this object because a different thread owns it. Even after using dispatcher 错误:调用线程无法访问此对象,因为其他线程拥有它。 故事板模拟 - Error:The calling thread cannot access this object because a different thread owns it. Storyboard simulation 调用线程无法访问该对象,因为其他线程拥有它。 调度员无法正常工作 - The calling thread cannot access this object because a different thread owns it. DISPATCHER NOT working 调用线程无法访问此对象,因为其他线程拥有 - The calling thread cannot access this object because a different thread owns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM