调用线程必须是STA,因为WPF中很多UI组件都需要这个 [英] The calling thread must be STA, because many UI components require this in WPF
问题描述
我的场景:
void Installer1_AfterInstall(object sender, InstallEventArgs e)
{
try
{
MainWindow ObjMain = new MainWindow();
ObjMain.Show();
}
catch (Exception ex)
{
Log.Write(ex);
}
}
我收到错误调用线程必须是 STA,因为许多 UI 组件都需要这个"
I got error "The calling thread must be STA, because many UI components require this"
我在做什么?
推荐答案
通常,WPF 线程的入口点方法为 ThreadMethod
设置了 [STAThreadAttribute]
,或者在使用 Thread.SetApartmentState()
创建线程时将单元状态设置为 STA.不过这个只能在线程启动前设置.
Normally, the entry point method for threads for WPF have the [STAThreadAttribute]
set for the ThreadMethod
, or have the apartment state set to STA when creating the thread using Thread.SetApartmentState()
. However, this can only be set before the thread is started.
如果您不能将此属性应用到您正在执行此任务的线程的应用程序的入口点,请尝试以下操作:
If you cannot apply this attribute to the entry point of the application of thread you are performing this task from, try the following:
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);
}
}
这篇关于调用线程必须是STA,因为WPF中很多UI组件都需要这个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!