Silverlight invalid cross-thread access exception

While working with Silverlight and MS CRM 2011 SOAP Endpoint , you might see this exception on the EndExecute function:

Invalid cross-thread access

The cause of this is related to doing the async call from a different thread than the Silverlight UI is running on, so while the call would still go through properly, the exception would hit when the Viewmodel would try to update the UI bound to its properties.

This happens many times when we try to update UI elements from a different thread in Silverlight( asynchronous callbacks), we will run into invalid cross-thread access error if a “Dispatcher.BeginInvoke” is not used.

i.e., The invalid cross-thread access error occurs from trying to update the ui from a non ui thread. Dispatcher.BeginInvoke will get you on the right thread.

Take a look at this method here on msdn.

The resolution to this is to add the dispatcher.invoke call to the Model on the async Callback.

this.Dispatcher.BeginInvoke(delegate()
            {
                //do something here
            });

However, this won’t work on static functions/methods, because for the reason, “this” can not be used in static function. In such scenarios , you could use :

System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate()
                {
                   //do something here
                });

Hope it helps !

Advertisements

About mytechlifedays

Its been a wonderful learning period over the last 6 years in the IT industry , getting exposed to whole lot of technologies and ideas. The hurdles and the crisis that came along have been wonderful experience ... And now its time to pen them down so that let some others execute faster and easily with these information .....
This entry was posted in MS CRM, Silverlight and tagged , , . Bookmark the permalink.

Leave a Reply ! It would be always appreciated ! :)

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s