如何防止新 STA 线程上的非模式窗口关闭
我想打开一些非模型窗口 (WPF),但此时我处于非 STA 线程上。所以我开始一个新线程并在那里打开它们。但一旦打开,它们就会再次关闭。 (顺便说一句。这些窗口的行为应该独立于主窗口。因此没有设置所有者属性)
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();
}
}
我在这里做错了什么?
I want to open some 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你希望你的窗口存活,你必须在创建它们后启动消息循环(否则你的线程就会退出,窗口没有机会渲染自己):(
在主线程中,消息循环是由框架创建的为你。)
PS:我不确定窗口是否可以被垃圾收集,所以我会在某个地方保留对它们的引用:
PPS:也许你希望你的窗口在主线程中运行?其实你可以这样做。您只需要以下内容:
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):
(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:
P.P.S.: Maybe you want your windows to run in the main thread? Actually you can do this. You need just the following:
线程在调用方法结束时死亡。将
ANewThread
放入一个字段(在类/表单级别声明它)。The Thread dies at the end of the calling method. Make
ANewThread
into a field (declare it at the class/Form level).