tags:

views:

1922

answers:

2

what is a difference between System.Windows.Forms.Timer() and System.Windows.Threading.DispatcherTimer() ? In which cases, we should use them? any best practices ?

+12  A: 

Windows.Forms.Timer uses the windows forms message loop to process timer events. It should be used when writing timing events that are being used in Windows Forms applications, and you want the timer to fire on the main UI thread.

DispatcherTimer is the WPF timing mechanism. It should be used when you want to handle timing in a similar manner (although this isn't limited to a single thread - each thread has its own dispatcher) and you're using WPF. It fires the event on the same thread as the Dispatcher.

In general, WPF==DispatcherTimer and Windows Forms==Forms.Timer.

That being said, there is also System.Threading.Timer, which is a timer class that fires on a separate thread. This is good for purely numerical timing, where you're not trying to update the UI, etc.

Reed Copsey
Thanks for your prompt response. So this means, whenever I want to have a timer related to UI, I should use DispatcherTimer, and when I want to fire a timer, which I don't want to freeze UL, I should use System.Threading.Timer in a separate thread. The second question is: if I want to use DispatcherTimer, and I want to have a timer not bound to the UI, should I call it in a separated thread by using System.Threading.Timer or still DisptacherTimer?
paradisonoir
It depends on what you're trying to do. I rarely use System.Threading.Timer - I usually would stick to Dispatcher Timer, and then do your WORK (which is what could block your UI) in another thread, using something like a BackgroundWorker. The timers really should never block your UI, unless you're doing "too much" work in their event handler.
Reed Copsey
I am having a problem with DispatcherTimer eating up processor over time. Is there a good way to handle that?
discorax
Check to see what specifically is eating up the cpu. Are you creating lots of timers, that aren't being stopped?
Reed Copsey
Make sure you set the interval property correctly.Don't do this:timer1.Interval = new TimeSpan(1000); // "1000" represents ticks not milliseconds!CPU was super high, until I corrected it with this:timer1.Interval = System.TimeSpan.FromSeconds(1);
LonnieBest
A: 

simple example in WPF on Digital Clock http://madhukaudantha.blogspot.com/2010/04/digital-clock-in-wpf.html

Madhuka