DispatchTimer: Silverlight’s Timer

You likely used the usual Timer class in C# for interval-based events, like so:

Timer everyFiveSeconds = new Timer(5000);
everyFiveSeconds .Elapsed += new ElapsedEventHandler(everyFiveSeconds _Elapsed);
everyFiveSeconds .Start();
// ... }
void everyFiveSeconds_Elapsed(object sender, ElapsedEventArgs e)
throw new NotImplementedException();

Well, those of you who move into Silverlight will be (unhappily!) surprised to find out that System.Timers doesn’t exist in Silverlight applications!

How, then, do we code the equivalent of this in Silverlight?

The answer is to use the DispatchTimer class; the equivalent of the above is:

DispatcherTimer everyFiveSeconds = new DispatcherTimer();
everyFiveSeconds.Interval = TimeSpan.FromSeconds(5);
everyFiveSeconds.Tick += new EventHandler(everyFiveSeconds_Tick);
// ... }
void everyFiveSeconds_Tick(object sender, EventArgs e)
throw new NotImplementedException();

Pretty simple. Changes are:

  • The constructor is parameterless.
  • And, as a consequence, the interval is set in a second step.
  • The event to add a listener for is called Tick, not Elapsed

Other than that, the timer works more or less as you expect.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Silverlight and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *