ApartmentState ApartmentState ApartmentState ApartmentState Enum

Definición

Especifica el estado de apartamento de un 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
Herencia
ApartmentStateApartmentStateApartmentStateApartmentState
Atributos

Campos

MTA MTA MTA MTA 1

Thread creará y entrará en un apartamento multiproceso.The Thread will create and enter a multithreaded apartment.

STA STA STA STA 0

Thread creará y entrará en un contenedor uniproceso.The Thread will create and enter a single-threaded apartment.

Unknown Unknown Unknown Unknown 2

No se ha establecido el valor de la propiedad ApartmentState.The ApartmentState property has not been set.

Ejemplos

En el ejemplo de código siguiente se muestra cómo establecer el estado de apartamento de un subproceso.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

Comentarios

Un contenedor es un contenedor lógico dentro de un proceso para los objetos que comparten los mismos requisitos de acceso de subproceso.An apartment is a logical container within a process for objects sharing the same thread access requirements. Todos los objetos en el mismo apartamento pueden recibir llamadas desde cualquier subproceso en el apartamento.All objects in the same apartment can receive calls from any thread in the apartment. .NET Framework no utiliza contenedores y objetos administrados son responsables de uso de todos los recursos compartidos de manera segura para subprocesos a sí mismos.The .NET Framework does not use apartments, and managed objects are responsible for using all shared resources in a thread-safe manner themselves.

Dado que las clases COM usan apartamentos, common language runtime debe crear e inicializar un apartamento al llamar a un objeto COM en una situación de interoperabilidad COM.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 subproceso administrado puede crear y escribir un contenedor uniproceso (STA) que permite que un único subproceso o un apartamento multiproceso (MTA) que contiene uno o varios subprocesos.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. Puede controlar el tipo de apartamento creado estableciendo el ApartmentState propiedad del subproceso en uno de los valores de la ApartmentState enumeración.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. Dado que un subproceso determinado solo puede inicializar un apartamento COM una vez, no se puede cambiar el tipo de contenedor después de la primera llamada al código no administrado.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.

Para obtener más información, consulte Thread, subprocesamiento administrado y no administrado, y interoperabilidad COM avanzada.For more information, see Thread, Managed and Unmanaged Threading, and Advanced COM Interoperability.

Se aplica a

Consulte también: