窗口在sepatarted线程中创建(并显示)后立即关闭

时间:2014-11-25 12:28:32

标签: c# wpf multithreading window sta

我试图实例化并显示一个Window,当我得到{"The calling thread must be STA, because many UI components require this."}的异常时,所以我在一个单独的STA线程中重新完成所有操作,如下所示:

var thread = new Thread(() =>
{
     notificationPopUp = new NotificationPopUpView(unreadNotifications.First().session_s,unreadNotifications.First().secondry_msg);
     notificationPopUp.Show();
});

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

现在窗口显示然后立即消失,我想这是因为线程终止了它的工作,因此内部声明的对象也死了,如果我是正确的,我应该怎么处理这个,我试着通过在[STAThread]方法之前,在所有者方法之前,在许多其他方法(绝望地)之前放置Main属性来避免此解决方案,但我仍然遇到同样的问题,我知道问题的标题是某种程度上不是很好描述,但我有点不得不提到这个STA的事情,这是我在创建线程之前得到的错误(只是为了向你提供整个数据):

enter image description here

所以我的主要问题是:为什么窗口立即关闭?

现在,因为它是因为它是在线程中创建的并且在线程完成工作后被释放,所以我应该知道我应该继续尊重STA线程调用者?提前谢谢。

1 个答案:

答案 0 :(得分:3)

嗯,你在新线程中创建了一个窗口,线程终止,然后谁将运行message loop

创建用户对象(Window,Form,Control)的线程必须运行其消息循环以响应操作系统发送的消息。

调用Dispatcher.Run运行消息循环。

var thread = new Thread(() =>
{
    notificationPopUp = new NotificationPopUpView(unreadNotifications.First().session_s,unreadNotifications.First().secondry_msg);
    notificationPopUp.Show();
    Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();