WPF .NET 每分钟触发一个事件的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/479376/
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
WPF .NET Best way to trigger an event every minute
提问by Simon Temlett
I have an app that needs to check a database table every minute. The table is indexed by the time of day and so the app needs to run this check every minute.
我有一个应用程序需要每分钟检查一次数据库表。该表按一天中的时间编制索引,因此应用程序需要每分钟运行一次此检查。
What's the best of way of doing this? I can create a background worker thread but if I set it to sleep for 60 secs after each check I will eventually miss a minute because of the overhead of calling the check.
这样做的最佳方法是什么?我可以创建一个后台工作线程,但是如果我在每次检查后将它设置为休眠 60 秒,我最终会因为调用检查的开销而错过一分钟。
Do I remember the minute I checked and then check, every 15 secs say and if the minute has changed performed the check then.
我记得我检查然后检查的那一刻吗,每 15 秒说一次,如果分钟改变了,那么执行检查。
Or is there some other approach I should use?
或者我应该使用其他方法吗?
I'm using WPF, VS2008 and VB.NET
我正在使用 WPF、VS2008 和 VB.NET
TIA,
TIA,
Simon
西蒙
回答by MrTelly
The DispatcherTimeris what you're after - just set the interval you want, and then attach a method to the Tick event - works a treat.
该DispatcherTimer是你追求的-只需设置所需的间隔,然后连接到Tick事件的方法-工作的享受。
回答by Ray Booysen
As MrTelly said, the DispatcherTimer is the way to do this. It is tightly integrated with the Dispatcher queue and makes sure that your callbacks are on the correct thread. Below are some good articles about this class. Some sample code is below detailing a basic example:
正如 MrTelly 所说,DispatcherTimer 是做到这一点的方法。它与 Dispatcher 队列紧密集成,并确保您的回调位于正确的线程上。下面是一些关于这个类的好文章。下面是一些示例代码,详细介绍了一个基本示例:
// DispatcherTimer setup
DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// Updating the Label which displays the current second
lblSeconds.Content = DateTime.Now.Second;
// Forcing the CommandManager to raise the RequerySuggested event
CommandManager.InvalidateRequerySuggested();
}
回答by lc.
Not sure about WPF, but in WinForms, there's a Timer control for this. If there isn't one, one way is the following loop:
不确定 WPF,但在 WinForms 中,有一个用于此的 Timer 控件。如果没有,一种方法是以下循环:
- Check if we're past the last minute set
- If not, sleep for a short time and check again
- Do stuff
- Check the current time
- Save the minute
- Sleep for 60000ms - current time(sec and ms part) - some value
- 检查我们是否已经过了最后一分钟
- 如果没有,睡一会儿再检查
- 做东西
- 查看当前时间
- 节省一分钟
- 睡眠 60000 毫秒 - 当前时间(秒和毫秒部分) - 一些值

