How to prevent non modal windows on a new STA thread from closing
I want to open som开发者_运维技巧e non model windows (WPF) but at the point that this has to happen I am on a non STA thread. So I start a new thread and open them on there. But as soon as the are opened they close again. (By the way. the behaviour of these windows should be independent from the mainwindow. So no owner property is set)
private void SomeMethod_OnA_NON_STA_Thread()
{
// some other work here
Thread ANewThread = new Thread(OpenSomeWindows);
ANewThread.SetApartmentState(ApartmentState.STA);
ANewThread.Start();
}
private void OpenSomeWindows()
{
TestWindow T;
for (int i = 0; i < 3; i++)
{
T = new TestWindow();
T.Show();
}
}
What am I doing wrong here?
If you want your windows to live, you have to start the message loop after you created them (otherwise your thread just exits, and the windows have no chance to render themselves):
private void OpenSomeWindows()
{
for (int i = 0; i < 3; i++)
{
TestWindow T = new TestWindow();
T.Show();
}
Dispatcher.Run(); // <---------
}
(In main thread, the message loop is created by the framework for you.)
P.S.: I am not sure whether the windows can be garbage collected, so I would keep references to them somewhere:
List<TestWindow> windows = new List<TestWindow>();
for (int i = 0; i < 3; i++)
{
TestWindow t = new TestWindow();
t.Show();
windows.Add(t);
}
Dispatcher.Run();
P.P.S.: Maybe you want your windows to run in the main thread? Actually you can do this. You need just the following:
private void SomeMethod_OnA_NON_STA_Thread()
{
// some other work here
Application.Current.Dispatcher.Invoke(OpenSomeWindows);
}
private void OpenSomeWindows()
{
for (int i = 0; i < 3; i++)
{
TestWindow T = new TestWindow();
T.Show();
}
// this way, no Dispatcher.Run is needed
}
The Thread dies at the end of the calling method. Make ANewThread
into a field (declare it at the class/Form level).
精彩评论