ApartmentState ApartmentState ApartmentState ApartmentState Enum

Définition

Spécifie l'état apartment (cloisonné) de Thread.Specifies the apartment state of a Thread.

public enum class ApartmentState
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public enum ApartmentState
type ApartmentState = 
Public Enum ApartmentState
Héritage
ApartmentStateApartmentStateApartmentStateApartmentState
Attributs

Champs

MTA MTA MTA MTA 1

Thread crée et entre un apartment (cloisonné) MTA (multithreaded apartment).The Thread will create and enter a multithreaded apartment.

STA STA STA STA 0

Thread crée et entre un thread cloisonné STA (single thread apartment).The Thread will create and enter a single-threaded apartment.

Unknown Unknown Unknown Unknown 2

La propriété ApartmentState n'a pas été définie.The ApartmentState property has not been set.

Exemples

L’exemple de code suivant montre comment définir l’état de cloisonnement d’un thread.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() );
   }

}

using System;
using System.Threading;

class ApartmentTest
{
    static void Main()
    {
        Thread newThread = 
            new Thread(new ThreadStart(ThreadMethod));
        newThread.SetApartmentState(ApartmentState.MTA);

        Console.WriteLine("ThreadState: {0}, ApartmentState: {1}", 
            newThread.ThreadState, newThread.ApartmentState);

        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, newThread.GetApartmentState());
        }
    }

    static void ThreadMethod()
    {
        Thread.Sleep(1000);
    }
}
Imports System.Threading

Public Class ApartmentTest

    <MTAThread> _
    Shared Sub Main()
    
        Dim newThread As Thread = New Thread(AddressOf ThreadMethod)
        newThread.SetApartmentState(ApartmentState.MTA)

        Console.WriteLine("ThreadState: {0}, ApartmentState: {1}", _
            newThread.ThreadState, newThread.GetApartmentState())

        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 stateException As ThreadStateException
            Console.WriteLine(vbCrLf & "{0} caught:" & vbCrLf & _
                "Thread is not In the Unstarted or Running state.", _
                stateException.GetType().Name)
            Console.WriteLine("ThreadState: {0}, ApartmentState: " & _
                "{1}", newThread.ThreadState, newThread.GetApartmentState())
        End Try

    End Sub

    Shared Sub ThreadMethod()
        Thread.Sleep(1000)
    End Sub

End Class

Remarques

Un cloisonnement est un conteneur logique au sein d’un processus pour les objets qui partagent les mêmes exigences d’accès aux threads.An apartment is a logical container within a process for objects sharing the same thread access requirements. Tous les objets du même cloisonnement peuvent recevoir des appels de n’importe quel thread du cloisonnement.All objects in the same apartment can receive calls from any thread in the apartment. Le .NET Framework n’utilise pas de cloisonnements, et les objets managés sont responsables de l’utilisation de toutes les ressources partagées de façon propre au thread.The .NET Framework does not use apartments, and managed objects are responsible for using all shared resources in a thread-safe manner themselves.

Étant donné que les classes COM utilisent des Apartments, le common language runtime doit créer et initialiser un cloisonnement lors de l’appel d’un objet COM dans une situation de COM Interop.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. Un thread managé peut créer et entrer un thread cloisonné (STA) qui autorise un seul thread, ou un cloisonnement multithread (MTA) qui contient un ou plusieurs threads.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. Vous pouvez contrôler le type de cloisonnement créé en affectant ApartmentState à la propriété du thread l’une des valeurs de l' ApartmentState énumération.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. Comme un thread donné ne peut initialiser qu’une seule fois un cloisonnement COM, vous ne pouvez pas modifier le type Apartment après le premier appel au code non managé.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.

Pour plus d’informations, Threadconsultez, gestion des threads managés et non managés, ainsi que l’interopérabilité com avancée.For more information, see Thread, Managed and Unmanaged Threading, and Advanced COM Interoperability.

S’applique à

Voir aussi