Monday, March 7, 2011

Timers in wpf

There are at least four timer classes in .NET, and three of them are named Timer.

The Timer classes in System.Threading and System.Timers can't be used in this particular program because the timer events occur in a different thread, and Freezable objects must be changed in the same thread in which they're created. The Timer class in System.Windows.Forms is an encapsulation of the standard Windows timer, but using it would require adding the System.Windows.Forms.dll assembly as an additional reference.

The DispatcherTimer class located in the System.Windows.Threading namespace is the one to use in WPF programs if you need the events to occur in the application thread. You set an Interval property from a TimeSpan property, but you can't get more frequent "ticks" than once every 10 milliseconds.

DispatcherTimer tmr = new  DispatcherTimer();
tmr.Interval = TimeSpan.FromMilliseconds(100);

tmr.Tick += TimerOnTick;
tmr.Start();



void TimerOnTick(object sender, EventArgs args)
{
//perform the logic here
}

No comments:

Post a Comment