I have this in my App.Xaml:
public App()
{
_backgroundWorker = new BackgroundWorker();
_backgroundWorker.DoWork += new DoWorkEventHandler(DoBackgroundWork);
_backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundCompleted);
_backgroundWorker.RunWorkerAsync();
_splashView = new SplashView();
_splashView.Show();
}
The DoBackgroundWork method performs some database setup, and then the BackgroundCompleted event closes the _splashView and shows _mainView.
However, modifying anything in the _splashView from BackgroundCompleted causes a cross thread exception, which is what I though background workers were designed to fix. I’m guessing this has something to do with the way backgroundworker’s work in App.Xaml. Maybe this is a bad way to do a splash screen?
There is no guarantee which thread the event handler of
OnWorkCompletedwill be used for execution.See similar question BackgroundWorker OnWorkCompleted throws cross-thread exception
You have to use the
InvokeorBeginInvokemethods to modify visual elements from a background thread. You can call this directly on the object whose properties you are modifying or use theDispatcher.EDIT: As per conversation with Adam
The
SynchronizationContexthas the desired effect for theOnWorkCompletedevent handler to be run on the initial thread (not the BackgroundWorker’s). http://msdn.microsoft.com/en-us/magazine/gg598924.aspx. (See Figure 2)If the BackgroundWorker is created and run prior to the SynchronizationContext initialization, then the
OnWorkCompletedwill execute on possibly the same thread as the BackgroundWorker.Thanks Adam.