Threading Issues C# Help

As discussed earlier in this chapter, a COM component marks the apartment (STAor MTA) it wants to live in, based on whether or not it is implemented as thread-safe.

However, the thread has to join an apartment.

What apartment.

The thread should join can be defined with the [STAThread] and
[MTAThread] attributes, which can be applied to the Main () method of an application.

The attribute [STAThread] means that the thread joins an STA,whereas the attribute [MTAThread] means that the thread joins an MTA.Joining an MTAis the default if no attribute is applied.

It is also possible to set the apartment state programmatically with the Apartment State property of the Thread class.

The Apartment State property allows you to set a value from the Apartment State enumeration.

Apartment State has the possible values STA and MTA (and unknown if it wasn’t set).

Be aware that the apartment stfte of a thread can be set only once.

If it is set a second time, the second
setting is ignored.

What happens if the thread chooses a different apartment from the apartments supported by the component? The correct apartment for the COM component is created automatically by the COM runtime.

However, the performance decreases if the apartment boundaries are crossed while calling the methods of a component.

Posted on October 27, 2015 in Interoperability

Share the Story

Back to Top