C#WPF例外

 life-death-swallow_204 发布于 2023-02-10 12:41

我正在使用WPF,在我的主窗口上,每当我尝试做任何事情时它都会给我这个错误"调用线程无法访问此对象,因为另一个线程拥有它." 这些例如,

this.Visibility = Visibility.Visible
((Storyboard)this.FindResource("HideWindow")).Begin()

我真的不知道那是什么,并且在大量需要帮助时我无法执行我的代码的第一行.更多信息:我无法打开另一个窗口,给我的线程不是STA错误

LoginWindow objLoginWindow = new LoginWindow();
objLoginWindow.ShowDialog();
objLoginWindow = null;

这是例外.

System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=The calling thread cannot access this object because a different thread owns it.
Source=WindowsBase
StackTrace: at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value) 
at Menupedia.LoadingWindow.OpenNewWindow() in c:\Users\xxxx\Desktop\menupedia\Menupediaa\Menupedia\LoadingWindow.xaml.cs:line 51 
at Menupedia.LoadingWindow.TimeElapsed(Object sender, ElapsedEventArgs e) in c:\Users\xxxx\Desktop\menupedia\Menupediaa\Menupedia\LoadingWindow.xaml.cs:line 39 
at System.Timers.Timer.MyTimerCallback(Object state)

Clemens.. 6

您的堆栈跟踪显示您使用了System.Timers.Timer.ElapsedTimer 的处理程序在后台线程中调用,后者不允许直接访问UI元素.您必须调用Dispatcher.InvokeDispatcher.BeginInvoke访问Elapsed处理程序中的UI元素.

但是,通过a替换Timer可能更容易System.Windows.Threading.DispatcherTimer,它具有Tick在UI线程中调用的事件,因此允许安全访问UI元素.

1 个回答
  • 您的堆栈跟踪显示您使用了System.Timers.Timer.ElapsedTimer 的处理程序在后台线程中调用,后者不允许直接访问UI元素.您必须调用Dispatcher.InvokeDispatcher.BeginInvoke访问Elapsed处理程序中的UI元素.

    但是,通过a替换Timer可能更容易System.Windows.Threading.DispatcherTimer,它具有Tick在UI线程中调用的事件,因此允许安全访问UI元素.

    2023-02-10 12:44 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有