Update the UI Asynchronously on a Timer

image_pdfimage_print


   
  

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF" Height="100" Width="300">
    <StackPanel>
        <Button x:Name="button" Click="Button_Click">Start Timer</Button>
        <TextBlock x:Name="txtStatus">
        </TextBlock>
    </StackPanel>
</Window>

//File:Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Threading;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        private DispatcherTimer timer;
         
        public Window1()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if(timer == null || !timer.IsEnabled)
            {
                timer = new DispatcherTimer();

                timer.Interval = TimeSpan.FromMilliseconds(1000);
                timer.Tick += new EventHandler(timer_Tick);

                timer.Start();
                button.Content = "Stop Timer";
            }
            else
            {
                timer.Stop();
                button.Content = "Start Timer";
            }
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            txtStatus.Text = DateTime.Now.Second.ToString();
        }
    }
}