调用线程必须是STA,因为许多UI组件在WPF中需要这个

时间:2010-11-15 10:56:27

标签: c# wpf

我的情景:

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

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

我收到错误“调用线程必须是STA,因为许多UI组件都需要这个”

我做什么?

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:4)

之前我遇到过这个错误,最简单的方法是使用Dispatcher  查看我的Questionanswer

祝你好运