Update UI With WPF Dispatcher And TPL

Introduction

WPF application works on the principle of  Thread affinity which means other threads can't interact with each other. This is called Single threaded apartment model.  Sometimes developers need to manage the thread or update WPF UI. But, WPF objects run on the principle of thread affinity that derives from the Dispatcher object. 
 
So, if developers create their own thread and try to update WPF UI then thread affinity principles stops them by using the method "VerifyAccess()" of DispatcherObject class. It will throw an exception “InvalidOperationException”.
 
So,  I will explain one code example by using "Dispatcher" and "TPL" by which you can update WPF UI. Below is the WPF code example
 
.XAML File:
  1. <Window x:Class="WpfApplication1.MainWindow"  
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.         Title="MainWindow" Height="350" Width="525">  
  5.     <StackPanel>  
  6.         <Label Name="myLabel"></Label>  
  7.     </StackPanel>  
  8. </Window>  
Here, I took one label - <Label Name="myLabel"></Label>
 
Go to code behind or .XAML.cs file: 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Windows;  
  7. using System.Windows.Controls;  
  8. using System.Windows.Threading;  
  9.   
  10. namespace WpfApplication1  
  11. {  
  12.     /// <summary>  
  13.     /// Interaction logic for MainWindow.xaml  
  14.     /// </summary>  
  15.     public partial class MainWindow : Window  
  16.     {  
  17.         public MainWindow()  
  18.         {  
  19.             InitializeComponent();  
  20.             var mySource = Enumerable.Range(1, 1000).ToList();  
  21.             Task.Factory.StartNew(() => CalculateMyOperation(mySource));  
  22.         }  
  23.   
  24.         private void CalculateMyOperation(List<int> values)  
  25.         {  
  26.             foreach (var i in values)  
  27.             {  
  28.                 var currentProgress = i;  
  29.                 Dispatcher.BeginInvoke(new Action(() =>  
  30.                 {  
  31.                     myLabel.Content = "Updating..." + currentProgress;  
  32.                 }), DispatcherPriority.Background);  
  33.             }  
  34.         }  
  35.     }  
  36. }  
Output:
 
Updating... 1
Updating ...2
Updating....3
...................
Updating...100
 
Here, I have used method "BeginInvoke" with Dispatcher because "Dispatcher.BeginInvoke" schedules the given action for execution in the UI thread and then returns control to allow the current thread to continue executing.
 
But, Invoke method blocks the caller until the scheduled action is completed.  
 
The priority of dispatcher describes the priority at which the operation can be invoked. Here, I used DispatcherPriority.Background as a dispatccher priorty. The Priority "Background" explains that I will start my operation after all other non-idle operations are complete.
 
I defined UI updating operations inside action delegate "new Action(() =>".

Note: Please find attached code for reference. 
 
Related Link: Threads in WPF 

Conclusion

Dispatcher is an important technique or concept to run an operation that will be executed on the UI thread. It updates the UI.
 
Read more articles on WPF:

Up Next
    Ebook Download
    View all
    Learn
    View all