Comparing Timer with DispatcherTimer

C#Timer

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

I've found good article about timers with small examples here: http://www.progware.org/Blog/post/Timers-in-WPF.aspx

As a conclusion:

> If DoSomething() manipulates GUI components then with the Timer you need to use: this.Dispatcher.Invoke((Action)delegate { //GUI RELATED CODE HERE} since you cannot access GUI controls from a different thread directly. With DispatcherTimer you do not need to do that. > > If DoSomething() performas a time-consuming task, then the GUI will freeze in the case of the DispatcherTimer. In the case of the Timer it won't since the long methos is executed in a different thread

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionparadisonoirView Question on Stackoverflow
Solution 1 - C#Reed CopseyView Answer on Stackoverflow
Solution 2 - C#SeekeerView Answer on Stackoverflow