简体   繁体   中英

The calling thread must be STA, because many UI components require this in WPF

My scenario:

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

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

I got error "The calling thread must be STA, because many UI components require this"

what i do?

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);
    }
}

I had that error before and the easiest way is using Dispatcher .
See my Question and answer

Good Luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM