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

我的情景:

void Installer1_AfterInstall(object sender, InstallEventArgs e) { try { MainWindow ObjMain = new MainWindow(); ObjMain.Show(); } catch (Exception ex) { Log.Write(ex); } } 

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

我所做的?

通常,WPF的线程的入口点方法具有为ThreadMethod设置的[STAThreadAttribute] ,或者在使用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); } } 

之前我遇到过这个错误,最简单的方法就是使用Dispatcher 。
看我的问题和answer

祝好运