I need to show a dialog box that is created with WPF from an MTA thread. I create a new thread, set it to be STA, and display the dialog there. But I cannot figure out from documentation if I actually need to call Dispatcher.Run() and then later shutdown the dispatcher before the thread terminates.
Thread thread = new Thread(() =>
{
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher));
dialog = new MyDialog();
dialog.Closed += (sender, e) => Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
dialog.Show();
Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
thread.Join();
I have found that the behavior appears to be the same if I instead do the following.
Thread thread = new Thread(() =>
{
dialog = new MyDialog();
dialog.ShowDialog();
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
thread.Join();
Do I actually need to setup the dispatcher, or does creating a WPF window and calling ShowDialog do that for me?
I noticed that the Window constructor calls Dispatcher.CurrentDispatcher, which will create a dispatcher if one does not exist. But I don't see any calls to Dispatcher.Run in the constructor or ShowDialog.