Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetApartmentState and [STAThread]

In Watin's source code, there is this piece of code:

    public void NavigateToNoWait(Uri url)
    {
        var thread = new Thread(GoToNoWaitInternal);
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start(url);
        thread.Join(500);
    }

    [STAThread]
    private void GoToNoWaitInternal(object uriIn)
    {
        var uri = (Uri)uriIn;
        NavigateTo(uri);
    }

Since the thread created has its apartment state set, why is the [STAThread] attribute added to the method? I am not interested in the specific piece of code, but I am wondering if STAThread attribute is needed at all.

Notes:

  • The method GoToNoWaitInternal isn't used elsewhere.
  • The whole watin project is about manipulating WebBrowser objects (Internet explorer windows in general). Thus, we are manipulating a COM Object.
like image 963
Odys Avatar asked Nov 28 '12 11:11

Odys


People also ask

What is Stathread?

STAThreadAttribute indicates that the COM threading model for the application is single-threaded apartment. This attribute must be present on the entry point of any application that uses Windows Forms; if it is omitted, the Windows components might not work correctly.

What is ApartmentState?

In . NET Framework versions 1.0 and 1.1, the ApartmentState property marks a thread to indicate that it will execute in a single-threaded or multithreaded apartment. This property can be set when the thread is in the Unstarted or Running thread state; however, it can be set only once for a thread.

What is MTA in c#?

MTA (Multi Threaded Apartment) is where many threads can all operate at the same time and the onus is on you as the developer to handle the thread security.


2 Answers

Just read the documentation for STAThreadAttribute (emphasis mine):

Apply this attribute to the entry point method (the Main() method in C# and Visual Basic). It has no effect on other methods. To set the apartment state of threads you start in your code, use the Thread.SetApartmentState method before starting the thread.

So, in this case, the attribute should have no effect.

like image 57
svick Avatar answered Sep 21 '22 18:09

svick


It should be noted that the STA (Single Threaded Apartment) is the threading model used by pre-.Net Visual Basic. It should only be used on the Main method of components that will be exposed to COM. The author of the code that you are trying to understand, appearantly did not understand how it is supposed to be used.

like image 37
Kevin Avatar answered Sep 19 '22 18:09

Kevin