2014-11-25 117 views
0

我试图实例化并显示一个窗口,当我收到一个异常说{"The calling thread must be STA, because many UI components require this."}所以我重新做了一个单独的STA线程如下所示:窗口在创建(并显示)后,立即关闭sepatarted线程

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方法之前,在所有者方法之前,在许多其他方法(绝望地)之前,但我仍然有相同的问题,我试图避免此解决方案,我kn ow问题的标题不太好描述,但我有点不得不提到这个STA的事情,这里是我创建线程之前得到的错误(只是为了提供整个数据):

enter image description here

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

现在,如果因为它是在线程中创建的,并且在线程完成工作后它被释放,那么我应该怎么做才能知道我应该保持尊重STA线程调用方?提前致谢。

+0

如果您搜索SO此错误信息,你会发现,它已经回答了无数次 – thumbmunkeys 2014-11-25 12:43:27

+0

@thumbmunkeys:我知道,但我不能保证这是针对我的具体情况,所以我没有”我真的明白这些问题的答案,考虑到我在SO和Google上做了最好的搜索,并且考虑到我是初学者,并且在这里发布这个问题是我唯一的避难所,因为我知道我会收到诸如你的意见,你会理解这一切并帮助我解决问题吗? 谢谢你在所有情况下... – AymenDaoudi 2014-11-25 12:47:28

回答

1

那么,你已经在新线程中创建了一个窗口,线程终止了,那么谁将运行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();