Coder Perfect

What is the purpose of [STATthread]?

Problem

I’m learning C# 3.5, and I’m curious as to what [STATthread] performs in our apps.

Asked by odiseh

Solution #1

In order for the Windows message pump to connect with COM components, the STAThreadAttribute is required. Although COM is not used in core Windows Forms, it is used in many other parts of the OS, such as system dialogs.

MSDN goes into a little more explanation about the cause behind this:

The necessity is also nicely explained in this blog article (Why is STAThread Required?). See this MSDN Magazine article from June 2004 for a more in-depth look at how the threading mechanism works at the CLR level (Archived, Apr. 2009).

Answered by Noldorin

Solution #2

It informs the compiler that the model is a Single Thread Apartment. This is an evil COM thing, it’s usually used for Windows Forms (GUI’s) as that uses Win32 for its drawing COM for drag and drop COM components (thanks @AnthonyWJones), which is implemented as STA. If you are using something that’s STA model from multiple threads then you get corrupted objects.

This is why, if you’ve done any forms coding, you’ll need to invoke into the Gui from another thread.

Don’t sweat it; simply accept that Windows GUI threads must be designated as STA otherwise strange things may happen.

Answered by Spence

Solution #3

More information can be found here. (June 2009, archived)

and

What is the purpose of STAThread?

Answered by rahul

Post is based on https://stackoverflow.com/questions/1361033/what-does-stathread-do