Search code examples
c#wpfbackgroundworker

WPF CrossThreadException in App.Xaml with BackgroundWorker


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?


Solution

  • There is no guarantee which thread the event handler of OnWorkCompleted will be used for execution.

    See similar question BackgroundWorker OnWorkCompleted throws cross-thread exception

    You have to use the Invoke or BeginInvoke methods to modify visual elements from a background thread. You can call this directly on the object whose properties you are modifying or use the Dispatcher.

    EDIT: As per conversation with Adam

    The SynchronizationContext has the desired effect for the OnWorkCompleted event 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 OnWorkCompleted will execute on possibly the same thread as the BackgroundWorker.

    Thanks Adam.