Silverlight 2 has a Timer (DispatcherTimer)

Before Silverlight 2, one had to conjure up various hacks to emulate a Timer.  One the most popular hacks was to use a StoryBoard that would continually call upon itself after completion.  This would end up looking something like the following:

   1:  public partial class Timer : UserControl
   2:  {
   3:   
   4:      public delegate void TimerFiredHandler();
   5:      public event TimerFiredHandler TimerFired;
   6:   
   7:      public Timer()
   8:      {
   9:          InitializeComponent();
  10:          TimeUnit.Completed += new EventHandler(TimeUnit_Completed);
  11:      }
  12:   
  13:      void TimeUnit_Completed(object sender, EventArgs e)
  14:      {
  15:          TimeUnit.Begin();
  16:          if (TimerFired != null)
  17:              TimerFired();
  18:      }
  19:      
  20:      public void StartTimer()
  21:      {
  22:          TimeUnit.Begin();
  23:      }
  24:  }
 

Consumers could then instantiate and execute the so-called Timer like so:

   1:  Timer t = new Timer();
   2:  Container.Children.Add(t);
   3:  t.TimerFired += new Timer.TimerFiredHandler(t_TimerFired);
   4:  t.StartTimer();
...

   1:  void t_TimerFired()
   2:  {
   3:      // Do Stuff here.
   4:  }

What can you say, it's a hack.  But that was then and this is now, check out the DispatcherTimer:

   1:  System.Windows.Threading.DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
   2:  dt.Interval = new TimeSpan(0, 0, 0, 0, 500); // 500 Milliseconds
   3:  dt.Tick += new EventHandler(dt_Tick);
   4:  dt.Start();
...
   1:  void dt_Tick(object sender, EventArgs e)
   2:  {
   3:      // Do Stuff here.
   4:  }
 

Enjoy!


Feedback

# re: Silverlight 2 has a Timer (DispatcherTimer)

Gravatar Good news 3/11/2008 3:36 AM | jhrecife

# re: Silverlight 2 has a Timer (DispatcherTimer)

Gravatar that's great.. thanks for sharing.. 3/12/2008 10:04 PM | Michael Sync

Comments have been closed on this topic.