COM Apartments


Threading was always an important topic with COM objects. COM defines apartment models. With a single-threaded apartment (STA), the COM runtime does the synchronization. A multithreaded apartment (MTA) means better performance but without synchronization by the COM runtime.

A COM component defines the apartment model it requires by setting a configuration value in the registry. A COM component that is developed in a thread-safe manner supports the MTA. Multiple threads can access this component at once, and the component must do synchronization on its own. A COM component that doesn’t deal with multiple threads requires a STA. Here, just one (and always the same) thread accesses the component. Another thread can access the component only by using a proxy that sends a Window message to the thread that is connected to the COM object. STAs use Windows messages for synchronization.

Visual Basic 6 components only supported the STA model. A COM component that is configured with the option both supports both STA and MTA.

While the COM component defines the requirements for the apartment, the thread that instantiates the COM object defines the apartment it is running in. This apartment should be the same one that the COM component requires.

A .NET thread by default runs in a MTA. Probably you’ve already seen the attribute [STAThread] with the Main() method of a Windows application. This attribute specifies that the main thread joins a STA. Windows Forms applications require an STA thread.

  [STAThread] static void Main() {    //... 

When creating a new thread, you can define the apartment model either by applying the attribute [STAThread] or [MTAThread] to the entry point method of the thread or by invoking the SetApartmentState() method of the Thread class before starting the thread:

  Thread t1 = new Thread(DoSomeWork); t1.SetApartmentState(ApartmentState.STA); t1.Start(); 

You can get the apartment of the thread with the GetApartmentThread() method.

Tip 

In Chapter 23, you can read about .NET interop with COM components and more about COM apartment models.




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net