我有一个应用程序需要每分钟检查一次数据库表。该表按一天中的时间编制索引,因此应用程序需要每分钟运行一次此检查。
这样做的最好方法是什么?我可以创建一个后台工作线程,但如果我在每次检查后将其设置为休眠 60 秒,我最终会因为调用检查的开销而错过一分钟。
我是否记得我检查的那一刻,然后检查,每 15 秒说一次,如果该分钟发生了变化,然后执行检查。
还是我应该使用其他方法?
我正在使用 WPF、VS2008 和 VB.NET
TIA,
西蒙
DispatcherTimer是您所追求的 - 只需设置所需的间隔,然后将方法附加到 Tick 事件 - 就可以了。
正如 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();
}
不确定 WPF,但在 WinForms 中,有一个 Timer 控件。如果没有,一种方法是以下循环: