【问题标题】:The calling thread must be STA, because many UI components require this in WPF [duplicate]调用线程必须是 STA,因为许多 UI 组件在 WPF 中都需要这个 [重复]
【发布时间】:2010-11-15 10:56:26
【问题描述】:

我的场景:

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

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

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

我在做什么?

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    通常,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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      相关资源
      最近更新 更多