Dispatcher In A Single Threaded WPF App

We have all worked with single-threaded & multi-threaded applications.
 
A WPF application always starts in a single-threaded apartment. Now, what is this single-threaded apartment?
 

Single-threaded apartment (STA)

 
As the name suggests single-threaded apartment contains only a single thread. And all the objects inside this apartment are managed by this thread. Objects don't need to be synchronized because all method calls are synchronous. So what if another thread tries to access an object of an STA application such as WPF?
 
.Net throws the following exception,
 
Let's create a login page to understand what are we talking about.
 
MainWindow.xaml
  1. <Window x:Class="A.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:A"    
  7.         mc:Ignorable="d"    
  8.         Title="MainWindow" Height="120" Width="250">    
  9.     <Grid>    
  10.         <Grid.RowDefinitions>    
  11.             <RowDefinition Height="Auto"/>    
  12.             <RowDefinition Height="Auto"/>    
  13.             <RowDefinition Height="Auto"/>    
  14.         </Grid.RowDefinitions>    
  15.         <Grid.ColumnDefinitions>    
  16.             <ColumnDefinition Width="Auto"/>    
  17.             <ColumnDefinition Width="Auto"/>    
  18.         </Grid.ColumnDefinitions>    
  19.         <Label x:Name="LabelUserName"    
  20.                Content="User Name:"/>    
  21.         <Label x:Name="LabelPassword"     
  22.                Content="Password:"    
  23.                Grid.Row="1"/>    
  24.         <TextBox x:Name="TextBoxUserName"    
  25.                  Height="20"    
  26.                  Width="150"    
  27.                  Grid.Column="1"/>    
  28.         <PasswordBox x:Name="TextBoxPassword"    
  29.                  Height="20"    
  30.                  Width="150"    
  31.                  Grid.Column="1"    
  32.                  Grid.Row="1"/>    
  33.         <Button x:Name="ButtonLogin"    
  34.                 Height="20"    
  35.                 Width="100"    
  36.                 Content="Login"    
  37.                 HorizontalAlignment="Center"    
  38.                 Margin="20 0 0 0"    
  39.                 Grid.Row="2"    
  40.                 Grid.ColumnSpan="2" Click="ButtonLogin_Click"/>    
  41.     </Grid>    
  42. </Window>    
Let's update code behind MainWindow.xaml.cs
  1. using System.Drawing;  
  2. using System.Threading;  
  3. using System.Windows;  
  4. using System.Windows.Media;  
  5.   
  6. namespace A  
  7. {  
  8.     /// <summary>  
  9.     /// Interaction logic for MainWindow.xaml  
  10.     /// </summary>  
  11.     public partial class MainWindow : Window  
  12.     {  
  13.         Thread MTA;  
  14.         public MainWindow()  
  15.         {  
  16.               
  17.             InitializeComponent();  
  18.             this.DataContext = new MainWindowViewModel();  
  19.         }  
  20.   
  21.         private void ButtonLogin_Click(object sender, RoutedEventArgs e)  
  22.         {  
  23.            MTA = new Thread(new ThreadStart(Login));  
  24.            MTA.Start();  
  25.         }  
  26.   
  27.         private void Login()  
  28.         {  
  29.             if(TextBoxUserName.Text != null)  
  30.             {  
  31.   
  32.             }   
  33.         }  
  34.     }  

Now inside a Login method is access by another thread, and it is trying to access TextBox's text property which is owned by our STA - WPF application.
 
Now if we try to run our application we will get the following error,
 
Dispatcher In A Single Threaded WPF App
 
Solution
 
WPF app needs a message queue to synchronize calls from other threads.

When other threads call an object in STA thread then the object call is queued in the message queue and STA; i.e., our WPF app, will receive a call from that message queue.
 
Dispatcher owns a message queue.
 
How it works
 
At runtime WPF application automatically creates a new dispatcher object and calls its run method.

The run method is used for initializing the message queue.
 
We know the WPF app runs on UI Thread, which is responsible for Animations, Control styles & data inputs.
 
WPF Dispatcher belongs to the UI thread. So in our example when we tried to access TextBox's Text property which was owned by a UI thread, then UI Thread queued the method call into the Dispatcher queue. The dispatcher then executes its message queue in a synchronized fashion.
 

Purpose of Dispatcher

 
We are good until we are only working with UI thread.

When we create a new thread to share the load of a UI Thread and want to update the UI from the Non-UI Thread then we have to use a dispatcher.
 
As we learned, only dispatcher can update the objects owned by UI Thread from a Non-UI Thread.
 
How to apply dispatcher in WPF
 
You can use the Invoke method of Dispatcher class and pass anonymous method or your method call.
  1. using System.Drawing;  
  2. using System.Threading;  
  3. using System.Windows;  
  4. using System.Windows.Media;  
  5.   
  6. namespace A  
  7. {  
  8.     /// <summary>  
  9.     /// Interaction logic for MainWindow.xaml  
  10.     /// </summary>  
  11.     public partial class MainWindow : Window  
  12.     {  
  13.         Thread MTA;  
  14.         public MainWindow()  
  15.         {  
  16.             InitializeComponent();  
  17.             this.DataContext = new MainWindowViewModel();  
  18.         }  
  19.   
  20.         private void ButtonLogin_Click(object sender, RoutedEventArgs e)  
  21.         {  
  22.             this.Dispatcher.Invoke(() => {  
  23.                 Login();  
  24.             });  
  25.         }  
  26.   
  27.         private void Login()  
  28.         {  
  29.             if(TextBoxUserName.Text != null)  
  30.             {  
  31.   
  32.             }   
  33.         }  
  34.     }  

Now if you run your program, you'll get no error: See the following image shows breakpoint has reached the access point where we were getting error previously.
 
Dispatcher In A Single Threaded WPF App
 
Here is the output,
 
Dispatcher In A Single Threaded WPF App
 
Now Invoke method runs synchronously, meaning it will wait until our Login method finishes its execution, then it will move forward with its execution.
 
But in heavy applications, we can't sit and wait until thread finishes its job.
 
For that purpose, Dispatcher provides another method BeginInvoke().
 
Now, this method runs asynchronously, meaning it will not wait until Login method finishes its execution, it will move forward with its execution without waiting.
 
BeginInvoke method returns the status of an ongoing operation, plus two events aborted and completed. All this is wrapped inside a DispatcherOperation object.
 
In order to call BeingInvoke you need to pass Action,
  1. private void ButtonLogin_Click(object sender, RoutedEventArgs e)  
  2.        {  
  3.            this.Dispatcher.BeginInvoke((Action)(() => {  
  4.                Login();  
  5.            }));  
  6.        } 
Well, that's all folks.
 
I hope you've come away from this with a real grasp of the Dispatcher and how it can be applied to your personal projects in the future.

If you've enjoyed the article, which I hope you have, please apply your knowledge to enliven the code in your projects.

If you have any questions or just want to connect, follow these links.
Happy coding folks.