Dispatcher in WPF – Demo

You can find below a simple application which will showcase the power of Dispatcher.
In the application below I will try to update a textbox with a value on button click but after waiting for 5000 ms. In WPF we can use dispatcher when we want to work on different thread and then attach it back to the main UI thread. Please find below the sample.

<Window x:Class="DispatcherDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition Height="100"/>
        </Grid.RowDefinitions>
        <Button Content="Click Me !!" FontSize="28" Grid.Row="0" Margin="64,0,111,0" Click="Button_Click_1"/>
        <TextBox x:Name="txtshow" Grid.Row="1" Margin="64,0,111,0"/>
    </Grid>
</Window>

As you can see above I want the textbox to display some value on button click.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DispatcherDemo
{
    class Sleep
    {
        public string Sleeper
        {
            get
            {
                Thread.Sleep(5000);
                return "i am awake";
            }
        }
    }
}

I have created a class ‘Sleep’ which has a getter of a property ‘Sleeper’. This getter will return its value after it has slept for 5000 ms 🙂 now find below the main task.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DispatcherDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Sleep obj = new Sleep();
        public MainWindow()
        {
            InitializeComponent();
            Debug.WriteLine("UI thread"+Thread.CurrentThread.ManagedThreadId);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("Click thread" + Thread.CurrentThread.ManagedThreadId);
            ThreadPool.QueueUserWorkItem(DoWork);
        }

        private void DoWork(object state)
        {
            Debug.WriteLine("Do Work thread" + Thread.CurrentThread.ManagedThreadId);
            string waking = obj.Sleeper;
            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,new Action<string> (updateUI),waking);
        }

        private void updateUI(string data)
        {
            Debug.WriteLine("Update UI thread" + Thread.CurrentThread.ManagedThreadId);
            txtshow.Text = data;
        }
    }
}

Here I am asking a Thread from the ThreadPool to perform my task since I don’t need the same UI thread to perform it as the window will hang for the stipulated time we have specified in the Thread.Sleep which will make my UI non-responsive. Once random thread performs my task I will have to attach it back to my main UI thread else it will thrown an Invalid Operation Exception.

2 thoughts on “Dispatcher in WPF – Demo

  1. Respected sir,
    I have canvas panel… Whenever I drag the desktop icon into my cavas panel, one more copy of that icon stored to be canvas panel…using XML. Help me to do this.

Leave a comment