How To Set the COM Apartment Type in Managed Threads

Article translations Article translations
Article ID: 318402 - View products that this article applies to.
This article was previously published under Q318402
Expand all | Collapse all

SUMMARY

This article describes how to set the Component Object Model (COM) apartment type that a managed thread enters.

MORE INFORMATION

When you start a managed thread, by default the thread does not enter any COM apartments. The managed thread enters an apartment implicitly when the first COM call is made from the thread. By default, the managed thread enters a multithreaded apartment (MTA) for the process. After a managed thread enters a COM apartment, it cannot leave and enter another apartment. You can cause a managed thread to enter a single-threaded apartment (STA) by using one of the following methods:
  1. Specify the [STAThread] directive on the main method of the application. When this method executes, it sets the ApartmentState property for that thread to STA.
  2. Set Thread.ApartmentState to System.Threading.ApartmentState.STA. This causes the thread to enter an STA. If you set Thread.ApartmentState to System.Threading.ApartmentState.MTA, the thread enters an MTA.
  3. Use the AspCompat = "true" attribute in the page directive on ASPX pages to cause the thread to enter an STA.
NOTE: In some cases in which the ApartmentState property is not initialized explicitly by using one of these methods and the thread has entered an apartment implicitly, the value of ApartmentState may be 2 (unknown). This occurs when the common language runtime cannot determine the type of the apartment without calling CoInitializeEx. This call indirectly initializes the apartment. In these cases, the common language runtime does not make this call, and returns unknown as the ApartmentState value.

REFERENCES

For more information, see the following Microsoft Developer Network (MSDN) Web sites:
Thread.ApartmentState Property
http://msdn.microsoft.com/en-us/library/system.threading.thread.apartmentstate(VS.71).aspx

STAThreadAttribute Class
http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx

MTAThreadAttribute Class
http://msdn.microsoft.com/en-us/library/system.mtathreadattribute.aspx

Properties

Article ID: 318402 - Last Review: February 23, 2007 - Revision: 5.6
APPLIES TO
  • Microsoft .NET Framework 1.0
  • Microsoft .NET Framework 1.1
Keywords: 
kbthread kbcominterop kbhowto KB318402

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com