How To Set the COM Apartment Type in Managed Threads (318402)



The information in this article applies to:

  • Microsoft .NET Framework 1.0
  • Microsoft .NET Framework 1.1

This article was previously published under Q318402

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.

Modification Type:MinorLast Reviewed:7/13/2004
Keywords:kbThread kbCOMInterop kbhowto KB318402