呼叫线程必须是STA,因为许多WPF的UI组件需要这个。

12

我的情况:

   void Installer1_AfterInstall(object sender, InstallEventArgs e)
    {
        try
        {         

              MainWindow ObjMain = new MainWindow();               
              ObjMain.Show();              
        }
        catch (Exception ex)
        {
            Log.Write(ex);
        }
    }

我收到了一个错误信息:“The calling thread must be STA, because many UI components require this”

我该怎么办?

1个回答

24

通常情况下,在 WPF 线程的入口方法中,[STAThreadAttribute] 被设置为 ThreadMethod,或者在使用 Thread.SetApartmentState() 创建线程时将公寓状态设置为 STA。然而,这只能在线程启动之前设置。

如果您无法将此属性应用于您正在执行此任务的应用程序或线程的入口点,请尝试以下操作:

void Installer1_AfterInstall(object sender, InstallEventArgs e)
{
    var thread = new Thread(new ThreadStart(DisplayFormThread));

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

private void DisplayFormThread()
{
    try
    {
        MainWindow ObjMain = new MainWindow();
        ObjMain.Show();
        ObjMain.Closed += (s, e) => System.Windows.Threading.Dispatcher.ExitAllFrames();

        System.Windows.Threading.Dispatcher.Run();
    }
    catch (Exception ex)
    {
        Log.Write(ex);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接