A .NET thread is automatically assigned an apartment upon entering apartment-savvy Win32 or legacy COM code. By default, it will be allocated a multi-threaded apartment, unless one requests a single-threaded apartment as follows:
Thread t = new Thread (...);
t.SetApartmentState (ApartmentState.STA);
One can also request that the main thread join a single-threaded apartment using the STAThread attribute on the main method:
class Program {
[STAThread]
static void Main() {
...
Apartments have no effect while executing pure .NET code. In other words, two threads with an apartment state of STA can simultaneously call the same method on the same object, and no automatic marshalling or locking will take place. Only when execution hits unmanaged code can they kick in.The types in the System.Windows.Forms namespace extensively call Win32 code designed to work in a single-threaded apartment. For this reason, a Windows Forms program should have have the [STAThread] attribute on its main method, otherwise one of two things will occur upon reaching Win32 UI code:
- it will marshal over to a single-threaded apartment
- it will crumble and fail.