I had a Invalid Cross Thread access issue, but a little research and I managed to fix it by using the Dispatcher.
Now in my app I have objects with lazy loading. I’d make an Async call using WCF and as usual I use the Dispatcher to update my objects DataContext, however it didn’t work for this scenario. I did however find a solution here. Here’s what I don’t understand.
In my UserControl I have code to call an Toggle method on my object. The call to this method is within a Dispatcher like so.
Dispatcher.BeginInvoke( () => _CurrentPin.ToggleInfoPanel() );
As I mentioned before this was not enough to satisfy Silverlight. I had to make another Dispatcher call within my object. My object is NOT a UIElement, but a simple class that handles all its own loading/saving.
So the problem was fixed by calling
Deployment.Current.Dispatcher.BeginInvoke( () => dataContext.Detail = detail );
within my class.
Why did I have to call the Dispatcher twice to achieve this? Shouldn’t a high-level call be enough? Is there a difference between the Deployment.Current.Dispatcher and the Dispatcher in a UIElement?
Ideally, store a single instance of
Dispatcherthat you can use elsewhere without having the thread check on it.Calling any singleton .Current instance may in fact cause a cross-thread access check to be invoked. By storing it first, you can avoid this to actually get the shared instance.
I use a “SmartDispatcher” that uses a dispatcher when called off-thread, and just invokes otherwise. It solves this sort of issue.
Post: http://www.jeff.wilcox.name/2010/04/propertychangedbase-crossthread/
Code: