Search code examples
wpfdispatcher

Open another xaml window with STA thread error


I am working with WPF. I run a thread process in the main xaml window using Dispatcher.

Then I got this error for opening another WPF to show the result of displaying a 3D image:

{"The calling thread must be STA, because many UI components require this."}

This is how I start a new window:

void DisplayFormThread()
{
    IResult result = _mainWindow.GetResult();
    ResultView resultView = new ResultView (result);
    resultView.Show();
}

I have tried to resolve the problem by adding this in some posts on Stack Overflow but it does not help:

ThreadStart start = delegate()
{
   DispatcherOperation op = Dispatcher.CurrentDispatcher.BeginInvoke(
        new delegateNewWindow(DisplayFormThread), DispatcherPriority.Background);
    
        DispatcherOperationStatus status = op.Status;
                   while (status != DispatcherOperationStatus.Completed)
                   {
                            status = op.Wait(TimeSpan.FromMilliseconds(1000));
                            if (status == DispatcherOperationStatus.Aborted)
                            {
                                 // Alert Someone
                            }
                    }
    
       };

// Create the thread and kick it started!
Thread thread = new Thread(start);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();

How can I solve the problem?


Solution

  • The reason is that our newly created thread is not enabled to support WPF window infrastructure. In particular, it provides no support for Windows message pumping,You have to run separate dispatcher for newly created window. Here is sample for this