Although @EBrown's answer already tells you how to use milliseconds with a DispatcherTimer
, its precision is supposedly around 15-20 ms, and the errors add up at each iteration, which makes it a bit impractical.
However it is possible to work around this issue by starting a System.Diagnostics.StopWatch
at the same time as the DispatcherTimer
and checking the StopWatch.ElapsedMilliseconds
inside the Tick Event with a smaller time step, and that seems to give more precise results. It also works with a System.Timers.Timer
.
Here's a short example based on a WPF program I made.
private void StartTimers(object sender, RoutedEventArgs e)
{
dtimer = new DispatcherTimer();
dtimer.Tick += new EventHandler(dTimer_Tick);
dtimer.Interval = TimeSpan.FromMilliseconds(1); // the small time step
stopWatch = new StopWatch();
dTimer.Start();
stopWatch.Start();
}
private void dTimer_Tick(object sender, EventArgs e)
{
currentTime = stopWatch.ElapsedMilliseconds;
if (currentTime - oldTime > interval)
{
oldTime = currentTime;
DoStuff();
}
}
Using StopWatch.Restart
in the Tick Event to do iterations will have the same error problem the DispatchTimer
causes, because it's going to restart when the DispatchTimer event is fired.