我的场景是:
void Installer1_AfterInstall(object sender, InstallEventArgs e)
{
try
{
MainWindow ObjMain = new MainWindow();
ObjMain.Show();
}
catch (Exception ex)
{
Log.Write(ex);
}
}我收到错误“调用线程必须是STA,因为许多UI组件都需要STA”
我做了什么?
发布于 2010-11-15 19:03:30
通常,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);
}
}https://stackoverflow.com/questions/4183622
复制相似问题