ApartmentState Enumeration

 
System_CAPS_noteNote

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Specifies the apartment state of a Thread.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)

[SerializableAttribute]
[ComVisibleAttribute(true)]
public enum class ApartmentState

Member nameDescription
MTA

The Thread will create and enter a multithreaded apartment.

STA

The Thread will create and enter a single-threaded apartment.

Unknown

The ApartmentState property has not been set.

An apartment is a logical container within a process for objects sharing the same thread access requirements. All objects in the same apartment can receive calls from any thread in the apartment. The .NET Framework does not use apartments, and managed objects are responsible for using all shared resources in a thread-safe manner themselves.

Because COM classes use apartments, the common language runtime needs to create and initialize an apartment when calling a COM object in a COM interop situation. A managed thread can create and enter a single-threaded apartment (STA) that allows only one thread, or a multithreaded apartment (MTA) that contains one or more threads. You can control the type of apartment created by setting the ApartmentState property of the thread to one of the values of the ApartmentState enumeration. Because a given thread can only initialize a COM apartment once, you cannot change the apartment type after the first call to the unmanaged code.

For more information, see Thread, Managed and Unmanaged Threading, and Advanced COM Interoperability.

The following code example demonstrates how to set the apartment state of a thread.

using namespace System;
using namespace System::Threading;
ref class ApartmentTest
{
public:
   static void ThreadMethod()
   {
      Thread::Sleep( 1000 );
   }

};

int main()
{
   Thread^ newThread = gcnew Thread( gcnew ThreadStart( &ApartmentTest::ThreadMethod ) );
   newThread->SetApartmentState(ApartmentState::MTA);

   Console::WriteLine( "ThreadState: {0}, ApartmentState: {1}", newThread->ThreadState.ToString(), newThread->GetApartmentState().ToString() );
   newThread->Start();

   // Wait for newThread to start and go to sleep.
   Thread::Sleep( 300 );
   try
   {

      // This causes an exception since newThread is sleeping.
      newThread->SetApartmentState(ApartmentState::STA);
   }
   catch ( ThreadStateException^ stateException ) 
   {
      Console::WriteLine( "\n{0} caught:\n"
      "Thread is not in the Unstarted or Running state.", stateException->GetType()->Name );
      Console::WriteLine( "ThreadState: {0}, ApartmentState: {1}", newThread->ThreadState.ToString(), newThread->GetApartmentState().ToString() );
   }

}

.NET Framework
Available since 1.1
Return to top
Show: