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

anb*_*van 12 c# wpf

我的情景:

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

              MainWindow ObjMain = new MainWindow();               
              ObjMain.Show();              
        }
        catch (Exception ex)
        {
            Log.Write(ex);
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

我所做的?

Pie*_*kel 24

通常,WPF的线程的入口点方法具有[STAThreadAttribute]set的设置ThreadMethod,或者在创建线程时使用设置为STA的单元状态Thread.SetApartmentState().但是,这只能在线程启动之前设置.

如果您无法将此属性应用于正在执行此任务的线程应用程序的入口点,请尝试以下操作:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

46054 次

最近记录:

14 年,6 月 前