Search code examples
wpfsilverlightprismunity-containerbackgroundworker

Unity Container Resolve in Background Thread


I have an event subscription from PRISM in Background Thread. After Login I load several Application related Data. Also I try to resolve the MainMenu from Unity Container.

MainMenu mainMenu = container.Resolve<MainMenu>();

This will end with an exception. It must be called from an STA Thread because the operations are GUI related. This seems totally understandable, but

  1. If I use the Dispatcher there is no Exception but it blocks the UI Thread, thats not what I want.
  2. Using another BackgroundWorker or Task Factory wont solve the problem, because its still in background Thread.

So how do I load GUI related stuff inside a background Thread?


Solution

  • Try creating a thread with the STA ApartmentState:

    Thread uiThread = new Thread(() =>
    {
        mainMenu = container.Resolve<MainMenu>();
    
        // Allow the main UI thread to proceed 
        System.Windows.Threading.Dispatcher.Run();     
    });               
    uiThread.SetApartmentState(ApartmentState.STA);
    uiThread.IsBackground = true;
    uiThread.Start();