Follow us on X (Twitter)  Like us on Facebook  Connect with us on LinkedIn  Subscribe to our YouTube Channel  Subscribe to our WhatsApp Group

What is Dispatcher object and why to use it in application?” - It’s a common question asked by beginners working in various XAML technologies like Silverlight, Windows Phone etc. I came to such instances many time when the developer has no clue about “Cross Thread Exception”.

 

That is the reason I wanted to publish this post mentioning the use of this Dispatcher object, mainly when you are getting an “Invalid cross-thread access” exception.

 

When you are working on a different thread like Background Worker, you may have to deal with the UI. Though you can do this by exposing properties and binding the properties with the UI elements but sometime it’s needed to access the UI element directly resulting a cross thread operation.

 

In case your background thread needs to access the UI thread directly for any update operation, you will get a nice message that says “Invalid cross-thread access” exception. That means, it can not access the data of an UI element from another thread directly.

 

UnauthorizedAccessException

 

So, here comes the use of Dispatcher object. Using the Dispatcher object, you will be able to access the UI thread directly and do any update operation on that. Dispatcher object of the application exposes a BeginInvoke() method, which allows us to access the UI thread easily.

 

You can either use a lambda expression to update the UI or directly call a method like this:

 
// using Lambda Expression while calling the BeginInvoke()
Dispatcher.BeginInvoke(() =>
            {
                textMessage.Text = "Update from different thread";
            });
 
 
// using direct method call from BeginInvoke()
Dispatcher.BeginInvoke(UpdateMyUI);

 

 

The importance of this Dispatcher object has significant effect on XAML technologies where we want to update the UI thread from any background thread. Without this, you will not be able to do the direct interactions between them on need basis and to stop the cross threading issues between them.

 

Hope, this post will be useful to those who are new in this technology, mainly Silverlight and experiencing a lot of difficulties in their application with this cross threaded exception. Still have question? Don’t hesitate to ask me below in the comment section and connect with me on Twitter and Facebook.

Have a question? Or, a comment? Let's Discuss it below...

dhgate

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.