Share via


Make a Silverlight Timer (Silverlight 2)

I've seen several questions related to timers on forums and in internal mail so I thought I'd toss up a simple example. To create a timer, you have to use the DispatcherTimer in the System.Windows.Threading namespace. 

Here's an example of a simple counter that uses DispatcherTimer: Run this sample.

And below is the code:

<Grid x:Name="LayoutRoot" Background="White">

    <!-- Just a TextBlock to show the output of the timer. -->
    <TextBlock Loaded="StartTimer" x:Name="myTextBlock" />
</Grid>

// C#
public void StartTimer(object o, RoutedEventArgs sender)
{
System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer();
myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); // 100 Milliseconds
myDispatcherTimer.Tick += new EventHandler(Each_Tick);
myDispatcherTimer.Start();
}

// A variable to count with.
int i = 0;

// Fires every 100 miliseconds while the DispatcherTimer is active.
public void Each_Tick(object o, EventArgs sender)
{
myTextBlock.Text = "Count up: " + i++.ToString();
}

Before Silverlight 2 (with Silverlight 1.0) you could create an animation using a Storyboard, however, Storyboards are for animations so this was a hack. Also, I believe the DispatcherTimer route offers better performance. Still, if you are using Silverlight 1.0 or have some reason for wanting to use a Storyboard to simulate a timer, see How to: Create a Timer in the Silverlight 1.0 documentation.

Sam Landstrom - MSFT

Comments