I've needed to use the equivilant of a System.Windows.Forms.Timer in WPF, and had a bit of trouble finding it. It's called DispatcherTimer - pretty much works the same except the Interval is specified using a TimeSpan instead of straight ms count. (Sample).
If you want to just do something later, you can get the Dispatcher (fancy wrapper around a message loop) and call BeginInvoke on it. The dispatcher can best be fetched by looking for a Dispatcher property on your UI element. (Sample).
The neat thing about the WPF version of BeginInvoke is that you can fine tune when you want it to be called. When you make a call to BeginInvoke you need to pass in a DispatcherPriority. I usually either pick Background (~= Application.Idle in Windows Forms) or Normal (~= BeginInvoke in Windows Forms).
4 comments:
Out of curiosity.. what's wrong with using System.Timers.Timer ?
The problem is System.Timers.Timer calls back at the exact moment the timer has elapsed. The only way it can do this is to interrupt what you're doing, and the only way to have that happen is to use a background thread.
So whenever you use a System.Timers.Timer, you need to carefully think about the thread safety of the objects you're touching.
On the other hand, both the WPF and Windows Forms timer messages are based off of WM_TIMER window message - when the interval has elapsed, a window message is generated. It calls back on the same thread that created it, so you don't have to worry about thread safety or (as much about) starvation.
Yes.. but still can't understand why you would need WPF/WinForm timers when you can still set SynchronizingObject to an UI object.
Or is SynchronizingObject not supported on WPF objects ?
You're welcome to take a lock or call Dispatcher.BeginInvoke or Dispatcher.Invoke in WPF (or the same methods on Control in Windows Forms), but what you're paying for is complexity - you're adding potentials for race conditions and deadlocks.
If the features you're getting from System.Timer is worth the complexity of using it correctly, then by all means use it.
Post a Comment