🔷 What is Dispatcher?
In WPF, the Dispatcher is used to execute code on the UI thread, especially when you’re working with background threads (like Task, Thread, BackgroundWorker, etc.).
Each UI element in WPF has a Dispatcher object because WPF enforces that only the thread that created a UI element can access it.
🔨 Example with Dispatcher.Invoke()
// Background thread
Task.Run(() =>
{
// This code is NOT on the UI thread
// Use Dispatcher to update UI safely
Application.Current.Dispatcher.Invoke(() =>
{
myLabel.Content = “Updated safely using Dispatcher”;
});
});
Here, Dispatcher.Invoke() is used to safely update myLabel on the UI thread from a background thread.
❌ What happens if you don’t use Dispatcher?
If you try to update a WPF UI element directly from a background thread (like inside Task.Run), you’ll get:
“InvalidOperationException: The calling thread cannot access this object because a different thread owns it.”
✅ How to check if Dispatcher is needed:
if (!Application.Current.Dispatcher.CheckAccess())
{
Application.Current.Dispatcher.Invoke(() =>
{
myLabel.Content = “Checked and updated safely”;
});
}
else
{
myLabel.Content = “Already on UI thread”;
}

