What is the use of Dispatcher object in XAML Technology?


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.


2 comments


  1. Hi Kunal, I am new to Silverlight. So can you please suggest me some more things..... If possible please send me some sample project details so that i will be more clarity. Please send me to sunil_sam1@yahoo.co.in.
    OR
    Some Project Details. That will be a great help.

    ReplyDelete


 
© 2008-2014 Kunal-Chowdhury.com | Designed by Kunal Chowdhury
Back to top