Development Tip – Dispatching calls to the UI thread

In Silverlight and WPF, if you wanted to update the UI from a thread you had launched, it was important that the UI update be executed on the UI thread, lest you get an invalid-cross-thread-access error.

You could ensure this by initially getting a pointer to the dispatcher for the UI thread, and then asking it to run your code. Something like this:

 _OriginalDispatcher = Application.Current.RootVisual.Dispatcher; 
 _OriginalDispatcher.BeginInvoke(myAction); 

In Win8 development, you don’t have to worry about this nearly as often, because the need to spin up new threads is greatly reduced by the availability of the await keyword. That having been said, if you do end up starting your own thread, here’s how you get the dispatcher:

 _OriginalDispatcher = Window.Current.CoreWindow.Dispatcher;