[英]Error when timer is elapsed and trying to show new Window C#
我的简单应用中有一个计时器:
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 3000;
aTimer.Enabled = true;
每次经过时都会调用此函数
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
...
DisplayWindow displayedWindow = new DisplayWindow();
displayedWindow.Show();
...
}
而displayedWindow
是WPF
表单,其中仅包含创建的代码本身(以及我的关闭按钮):
public partial class DisplayWindow : Window
{
public DisplayWindow()
{
InitializeComponent();
}
private void cancelButton_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
当我运行我的应用程序时,出现错误
public DisplayWindow()
有这样的消息:
"The calling thread must be STA, because many UI components require this".
我正在尝试阅读一些线程,而我刚发现是和我做过的STA Thread一起玩,但是没有成功。 我该如何解决这个问题?
如果WPF应用程序中使用了System.Timers.Timer,则值得注意的是System.Timers.Timer在不同于用户界面(UI)线程的线程上运行。 为了访问用户界面(UI)线程上的对象,必须使用Invoke或BeginInvoke将操作发布到用户界面(UI)线程的Dispatcher上。 使用与System.Timers.Timer相反的DispatcherTimer的原因是DispatcherTimer与Dispatcher在同一线程上运行,并且可以在DispatcherTimer上设置DispatcherPriority。
考虑为此使用DispatcherTimer
:
var timer = new DispatcherTimer();
timer.Tick += OnTimedEvent;
timer.Interval = TimeSpan.FromSeconds(3);
timer.Start();
并且,将您的处理程序签名更改为:
private static void OnTimedEvent(object sender, EventArgs e)
在timer事件中,要求UI调用您的方法,而无需当场调用它。 UI线程稍后将尽快调用您的方法。
这是一个来自MSDN的示例。 我将它留给您以相应地调整您的计时器处理程序:
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.