This is a mirror of official site: http://jasper-net.blogspot.com/

Getting an invalid cross-thread exception in Silverlight?

| Tuesday, February 1, 2011
Image this: you’re working on a Silverlight application, using the MVVM pattern, and you want to do something with the result of an async request (for example, you’re fetching persons, and you want to add them to a list in your VM when the operation completes).  Something like this:

PersonServiceReference.PersonServiceClient client =
new PersonServiceReference.PersonServiceClient();
         
client.LoadPersonsCompleted += (s, a) =>
{
   if (a.Error == null)
   {
       AllPersons = new ObservableCollection<Person>(a.Result);
    }
};
client.LoadPersonsAsync();

However, when you do this, you get an “invalid cross-thread exception” (if AllPersons is bound to a list in your UI).  What does this mean?  Simply put, you’re trying to access the UI thread (as the list you’re manipulating is bound to something in your UI), but you’re doing this from another thread: the thread on which your async operation runs.

Luckily, this is pretty easy to solve: invoke the Dispatcher as such and you’ll get rid of above exception:

Dispatcher.BeginInvoke(() =>
{
// your code
});

Read more: kevin dockx / icecream

Posted via email from Jasper-net

0 comments: