Labels

Monday, June 15, 2009

Threading || Apartment Model

Apartment Model

 

An apartment is a logical "container" for threads. Apartments come in two sizes – "single" and "multi".

An STA contains just one thread; MTA can contain any number of threads.

 

·         Apartment threading is an automatic Thread-Safety System, closely allied to COM – Microsoft's legacy.

·         Though .NET largely breaks free of this legacy models, there are times when it still crops up because of the need to interoperate with older Win32 APIs.

·         Apartment threading is most relevant to Windows Forms, because much of Windows Forms uses or wraps the long-standing Win32 API.

 

A .NET thread is By Default Allocated MTA, unless one requests a STA as follows:

 

 

Thread t = new Thread (...);

t.SetApartmentState (ApartmentState.STA);

 

 

 

Otherwise one can also request that the main thread join a STA using the STAThread attribute on the main method:.

 

 

class Program

{

  [STAThread]

  static void Main()

  {

    // Code Here

  }

}

 

 

 

·         Apartments have no effect while being with STA and 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 STA. 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 STA

·         It will crash.

 

Hope this helps.

 

Thanks & Regards,

Arun Manglick || Senior Tech Lead

 

 

No comments:

Post a Comment