December 17, 2009

WPF Timer (DispatcherTimer )

Comparison of different timers in .NET is found here. Unfortuneately this does not mention the DispatchTimer which is more appropriate for WPF usage (but not only)
using System.Windows.Threading;
...
private DispatcherTimer timer;    
...
const int MILLISECOND = 10000L;
timer = new DispatcherTimer();  
// Disable (stop) it 
timer.IsEnabled = false;
// Set timer event interval
timer.Interval = new TimeSpan(3000L * MILLISECOND);
// Timer events
timer.Tick += new EventHandler(timer_Tick);
...
timer.Start(); // at some point start the timer
...
void timer_Tick(object sender, EventArgs e)
{
  if (...)
  {
    timer.Stop();
  }
}

No comments: