【问题标题】:Window closes immediately after being created (and shown) in a sepatarted thread窗口在分隔线程中创建(并显示)后立即关闭
【发布时间】:2014-11-25 12:28:31
【问题描述】:

我试图实例化并显示一个窗口,当我得到一个异常说 {"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 的事情,这是我在创建线程之前遇到的错误(只是为了向您提供整个数据):

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

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

【问题讨论】:

  • 如果你在SO上搜索这个错误信息,你会发现已经回答了无数次了
  • @thumbmunkeys :我知道,但我不能确保它针对的是我的具体案例,所以我并没有真正理解这些问题的答案,考虑到我在 SO 上做了最好的搜索谷歌,考虑到我是初学者,在这里发布问题是我唯一的避难所,知道我会收到像你这样的 cmets,你会理解所有这些并帮助我解决问题吗?在所有情况下都谢谢你......

标签: c# wpf multithreading window sta


【解决方案1】:

好吧,你在新线程中创建了一个窗口,线程终止了,那么谁来运行message loop

创建用户对象(窗口、窗体、控件)的线程必须运行其消息循环以响应操作系统发送的消息。

调用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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多