DispatcherTimer in WPF

This blog shows how to change time at a fixed interval like in second, minute, hour using Dispatcher Timer. Set a timer interval, set a handler for the Tick event.

DispatcherTimer is the regular timer. It fires its Tick event on the UI thread, you can do anything you want with the UI. System.Timers.Timer is an asynchronous timer; its Elapsed event runs on a thread pool thread.

Let’s add a TextBlock control:

  1. <Window x:Class="TimersAndAnimationInXAML.MainWindow"  
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  6. xmlns:local="clr-namespace:TimersAndAnimationInXAML"  
  7. mc:Ignorable="d"  
  8. Title="MainWindow" Height="350" Width="525">  
  9. <Grid>  
  10. <TextBlock Name="txtName" FontFamily="Verdana"  
  11. FontSize="50" HorizontalAlignment="Center"  
  12. VerticalAlignment="Center" Foreground="#FFEA2525"></TextBlock>  
  13. </Grid>  
  14. </Window>  

Now create object of Dispatcher Timer and set interval time and fire Tick event and at last start timer.

  1. using System;  
  2. using System.Windows;  
  3. using System.Windows.Threading;  
  4. namespace TimersAndAnimationInXAML  
  5. {  
  6. /// <summary>  
  7. /// Interaction logic for MainWindow.xaml  
  8. /// </summary>  
  9. public partial class MainWindow : Window  
  10. {  
  11. public MainWindow()  
  12. {  
  13. InitializeComponent();  
  14. DispatcherTimer timer = new DispatcherTimer();  
  15. timer.Interval = TimeSpan.FromSeconds(1);  
  16. timer.Tick += Timer_Tick;  
  17. timer.Start();  
  18. }  
  19. private void Timer_Tick(object sender, EventArgs e)  
  20. {  
  21. txtName.Text = DateTime.Now.ToString("h:mm:ss tt");  
  22. }  
  23. }  
  24. }  
Run the project to see output: 


  1. public MainWindow()  
  2. {  
  3. InitializeComponent();  
  4. DispatcherTimer timer = new DispatcherTimer();  
  5. timer.Interval = TimeSpan.FromSeconds(1);  
  6. timer.Tick += Timer_Tick;  
  7. timer.Start();  
  8. }  
  9. private void Timer_Tick(object sender, EventArgs e)  
  10. {  
  11. txtName.Text = DateTime.Now.ToString();  
  12. }  

  1. public MainWindow()  
  2. {  
  3. InitializeComponent();  
  4. DispatcherTimer timer = new DispatcherTimer();  
  5. timer.Interval = TimeSpan.FromSeconds(1);  
  6. timer.Tick += Timer_Tick;  
  7. timer.Start();  
  8. }  
  9. private void Timer_Tick(object sender, EventArgs e)  
  10. {  
  11. txtName.Text = DateTime.Now.ToString("HH:mm:ss.fff");  
  12. }  

Conclusion

In this blog we have learned about DispatcherTimer class using WPF. If you have any question or comment, drop me a comment in C# Corner comments section.

Ebook Download
View all
Learn
View all