WPF .NET Best way to trigger an event every minute

2019-01-17 19:58发布

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.

Do I remember the minute I checked and then check, every 15 secs say and if the minute has changed performed the check then.

Or is there some other approach I should use?

I'm using WPF, VS2008 and VB.NET

TIA,

Simon

标签: .net wpf timer
3条回答
淡お忘
2楼-- · 2019-01-17 20:42

The DispatchTimer is what you're after - just set the interval you want, and then attach a method to the Tick event - works a treat.

查看更多
贼婆χ
3楼-- · 2019-01-17 20:51

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:

  • 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
查看更多
Lonely孤独者°
4楼-- · 2019-01-17 21:05

As MrTelly said, the DispatcherTimer is the way to do this. It is tightly intergrated 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:

//  DispatcherTimer setup
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();
}

Timer vs DispatcherTimer

MSDN Documentation

查看更多
登录 后发表回答