C# 如何在 WPF 中创建计时器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11559999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create a timer in WPF?
提问by user27
I am a newbie in timer in wpf and I need a code that every 5mins there is a message box will pop up. .can anyone help me for the simple code of timer.
我是 wpf 计时器的新手,我需要一个代码,每 5 分钟就会弹出一个消息框。.任何人都可以帮助我了解计时器的简单代码。
That's what I tried so far:
这就是我到目前为止所尝试的:
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
private void test()
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// code goes here
}
private void button1_Click(object sender, RoutedEventArgs e)
{
test();
}
采纳答案by Rhys Towey
In WPF, you use a DispatcherTimer.
在 WPF 中,您使用DispatcherTimer.
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,5,0);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// code goes here
}
回答by JasonDWilson
Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.
补充以上内容。如果您希望将滴答事件编组回 UI 线程,则可以使用 Dispatch 计时器。否则我会使用 System.Timers.Timer。

