Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 670
anbuselvan Avatar asked Nov 15 '10 10:11

anbuselvan


1 Answers

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);
    }
}
like image 61
Pieter van Ginkel Avatar answered Nov 10 '22 07:11

Pieter van Ginkel