WPF .NET Best way to trigger an event every minute

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


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

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:

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

Timer vs DispatcherTimer

MSDN Documentation

Tags:

.Net

Timer

Wpf