Click here to Skip to main content
15,885,869 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
How do i add a timer to a WPF it doesn't look possible
Posted
Comments
Sergey Alexandrovich Kryukov 23-May-11 2:26am    
You statement does look not true. What shall we do about it?
--SA

 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 23-May-11 2:40am    
May be useful samples for OP, my 5.
Please see my answer where I list all the possibilities (hopefully).
--SA
Have a look at the DispatcherTimer[^] class in WPF.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 23-May-11 2:37am    
Great, my 5.
I forgot about this one, but mentioned to general-purpose options, please see.
--SA
Abhinav S 23-May-11 2:37am    
No problem Thanks for the 5.
WPF is the abbreviated "Windows Presentation Foundation". You cannot "add" a timer for a foundation.
Timers already exist you should only use them. There are three types of timers: System.Threading.Timer and System.Timers.Timer are quite suitable for use with WPF, but System.Windows.Forms.Timer is not. Frankly, the last one is not very good even for use with Forms, it's just very well simplified. Don't try to use it and you will be fine. Use first two types instead.

See:
http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx[^],
http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx[^].

[EDIT]
Completely forgot about System.Windows.Threading.DispatcherTimer, Abhinav reminded us about.
[END EDIT]

Note that I don't believe you really need a timer. In most cases it's much better to use a thread, possible calling System.Threading.Thread.Sleep. This approach is usually a good replacement of using the timer; it's more robust and gives you much less trouble.

—SA
 
Share this answer
 
v2
Comments
Abhinav S 23-May-11 2:37am    
Good approaches. 5.
Sergey Alexandrovich Kryukov 23-May-11 2:39am    
Thank you, I also credited you for mentioned one more timer I forgot.
--SA
Abhinav S 23-May-11 8:31am    
Yes. Noticed that thank you.
CS2011 23-May-11 3:01am    
My 5+ explanation. Very good answer
Sergey Alexandrovich Kryukov 23-May-11 9:32am    
Thank you very much.
--SA
You can also add "standard" timer. But, you have to add little trick at it's Elapsed event handler:

C#
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Dispatcher.Invoke(new Action(()=>
         {
              ANY ACTIONS HERE
         }), null);
}


You have to call Invoke method, because Dispatcher handles flow in main thread in WPF.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900