Reputation: 248
I am invoking a service module call from my viewmodel in the background thread by using a background worker, all fine and dandy.
The service module method has an action parameter which is invoked when the service returns. Now I need to get back to the UI thread at this point to invoke the action (I have also tried getting back to the UI thread in my viewmodel method which is invoked from the service module.)
So to the crux of the matter I have tried
Application.Current.RootVisual.Dispatcher.BeginInvoke(() => code stuff here);
Which produces invalid cross thread access (fine I cant get to rootvisual here I understand)
I then tried to get the Dispatcher a different way as below
Deployment.Current.Dispatcher.BeginInvoke() => code here);
I have also tried a static class which has a Dispatcher property which I set in my application startup method and then try invoke using that.
Whilst using the Deployment dispatcher and my static class's dispatcher do not produce invalid cross thread access, the crux that has me so confused is that if i breakpoint inside the code that is being invoked by these dispatchers then I get this System.Threading.Thread.CurrentThread.ThreadState is Background
I can however update my properties in my view model and the view does indeed update without an issue, but I want to know if there is still something going wrong here and this will be a problem in the future.
Upvotes: 0
Views: 558
Reputation: 81243
To get to the UI dispactcher you can use this code -
Application.Current.Dispatcher.BeginInvoke() => code here);
For your comment -
I should add the most confusing part is from what I've read using a dispatcher is meant to guarantee you get back onto the UI thread!
You have misinterpreted that invoking a delegate on UI dispatcher will take you to UI thread, the above piece of code invocation will only queue the delegate on UI dispatcher and will execute on the UI thread. However, execution point will be there on the background thread from where you are calling this action.
These links might be useful to you - Understanding Dispatcher and Overview of dispatcher
Upvotes: 2