类型'System.InvalidOperationException'的异常 [英] exception of type 'System.InvalidOperationException'
本文介绍了类型'System.InvalidOperationException'的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨
我有一个计时器,在过去的事件中,我想更改WindowState.但我收到此错误:
调用线程无法访问该对象,因为其他线程拥有它.
我应该怎么办?这是一个WPF项目
好的,这是我的代码
Hi
I have a timer which in Elapsed Event i want to change the WindowState. but i get this error:
The calling thread cannot access this object because a different thread owns it.
what should i do? it''s a WPF project
ok here is my code
System.Timers.Timer timer=new System.Timers.Timer();
private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
this.WindowState = System.Windows.WindowState.Minimized;
timer.Interval = 5 * 1000;
timer.Enabled = true;
timer.AutoReset = true;
timer.Start();
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
timer.Enabled = false;
this.WindowState = System.Windows.WindowState.Normal;
.....
timer.Enabled = true;
timer.Start();
}
catch (Exception ex)
{
Logger.Log("OnTimer Error:" + ex.Message);
}
}
推荐答案
我认为,当您提取片段时,您会有点热情-该代码将无法正常工作.
计时器还有其他功能吗?我怀疑您这样做了,因为附加事件处理程序的代码不存在,这意味着缺少其他代码.
我想问题是计时器在表单完全准备就绪之前就在触发,这是我可以想到的将其设置为正常"失败的唯一原因.
因此,请检查您的代码-看看附加了事件处理程序的代码在计时器启动之前是否已准备好计时器和表单.
I think when you extracted the fragment you got a bit enthusiastic - that code won''t work.
Do you do anything else with the timer? I suspect you do, because the code to attach the event handler is not there, which implies that there is additional code missing.
I would guess that the problem is that the timer is firing before the form is fully ready, and that is the only reason I can think of for the set to Normal failing.
So check your code - see if the code which attaches the event handler has the timer and the form fully ready before the timer fires.
这篇关于类型'System.InvalidOperationException'的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文