WPF Timer

Jose Leon

In windows forms we had class called Timer that allowed us to execute a certain piece of code in our application in a predefined schedule. In WPF we have better class called the DispatchTimer. Using this class we can schedule a event to trigger depending on a certain amount of time that we specify.

Below you can find a XAML mark up of an application that simulates a stop watch:

               Start                Stop

And this is the C# code:

namespace WpfApplication6{    ///     /// Interaction logic for MainWindow.xaml    ///     public partial class MainWindow : Window    {        private DispatcherTimer timer;        public MainWindow()        {            InitializeComponent();            timer = new DispatcherTimer();            timer.Interval = TimeSpan.FromSeconds(1);            timer.Tick += timer_Tick;        }        void timer_Tick(object sender, EventArgs e)        {            TimerLabel.Content = DateTime.Now.ToLongTimeString();        }        private void StartButton_Click(object sender, RoutedEventArgs e)        {            timer.Start();        }        private void StopButton_Click(object sender, RoutedEventArgs e)        {            timer.Stop();        }    }}

In the code above, we're setting up a timer variable and creating an instance of it in the window constructor. We're then setting the inverval in which the timer should trigger to one second. The next line just sets up the event that will handle when the trigger actually fires. When the event executes, it basically sets the content of the TimerLabel to the actual time.

Timer Tick

The timer tick is the property where we can configure the event that will be triggered when the timer interval lapses. In our code above, is executing the method timer_Tick

Timer and the UI

The interesting thing about DispatchTimer is that it executes on the Dispatcher queue which runs on separate thread than the one our application runs. This means, that when the timer runs and triggers the Tick event, I can actually draw on the screen with any lags, giving us the opportunity to do any kind of animation and screen updating as needed.


All posts

  • licensing
  • analytics

Easy .NET Protection

Purchase template