ApartmentState Enumeração
Definição
public enum class ApartmentState
public enum ApartmentState
[System.Serializable]
public enum ApartmentState
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum ApartmentState
type ApartmentState =
[<System.Serializable>]
type ApartmentState =
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ApartmentState =
Public Enum ApartmentState
- Herança
- Atributos
Campos
| MTA | 1 | O Thread vai criar e inserir um Multi-Threaded Apartment.The Thread will create and enter a multithreaded apartment. |
| STA | 0 | O Thread vai criar e inserir um Single-Threaded Apartment.The Thread will create and enter a single-threaded apartment. |
| Unknown | 2 | A propriedade ApartmentState não foi definida.The ApartmentState property has not been set. |
Exemplos
O exemplo de código a seguir demonstra como definir o estado de apartment de um 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
Comentários
Um apartamento é um contêiner lógico dentro de um processo para objetos que compartilham os mesmos requisitos de acesso de thread.An apartment is a logical container within a process for objects sharing the same thread access requirements. Todos os objetos no mesmo apartamento podem receber chamadas de qualquer thread no apartamento.All objects in the same apartment can receive calls from any thread in the apartment. O .NET Framework não usa Apartments, e os objetos gerenciados são responsáveis por usar todos os recursos compartilhados de uma forma thread-safe.The .NET Framework does not use apartments, and managed objects are responsible for using all shared resources in a thread-safe manner themselves.
Como as classes COM usam Apartments, o Common Language Runtime precisa criar e inicializar um apartamento ao chamar um objeto COM em uma situação de interoperabilidade 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. Um thread gerenciado pode criar e inserir um STA (single-threaded apartment) que permite apenas um thread ou um MTA (multithreaded apartment) que contém um ou mais 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. Você pode controlar o tipo de apartment criado definindo a ApartmentState Propriedade do thread como um dos valores da ApartmentState enumeração.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. Como um determinado thread pode inicializar apenas um apartamento COM uma vez, você não pode alterar o tipo de apartamento após a primeira chamada para o código não gerenciado.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 obter mais informações, Thread consulte threads gerenciados e não gerenciadose interoperabilidade com avançada.For more information, see Thread, Managed and Unmanaged Threading, and Advanced COM Interoperability.