Thread.ApartmentState Propriedade
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Cuidado
The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.
Cuidado
The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.
Cuidado
Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.
Obtém ou define o estado de apartment desse thread.
public:
property System::Threading::ApartmentState ApartmentState { System::Threading::ApartmentState get(); void set(System::Threading::ApartmentState value); };
[System.Obsolete("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.", false)]
public System.Threading.ApartmentState ApartmentState { get; set; }
[System.Obsolete("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.")]
public System.Threading.ApartmentState ApartmentState { get; set; }
public System.Threading.ApartmentState ApartmentState { get; set; }
[System.Obsolete("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
public System.Threading.ApartmentState ApartmentState { get; set; }
[<System.Obsolete("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.", false)>]
member this.ApartmentState : System.Threading.ApartmentState with get, set
[<System.Obsolete("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.")>]
member this.ApartmentState : System.Threading.ApartmentState with get, set
member this.ApartmentState : System.Threading.ApartmentState with get, set
[<System.Obsolete("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")>]
member this.ApartmentState : System.Threading.ApartmentState with get, set
Public Property ApartmentState As ApartmentState
Valor da propriedade
Um dos valores de ApartmentState. O valor inicial é Unknown
.
- Atributos
Exceções
É feita uma tentativa de definir esta propriedade para um estado que não é um estado de apartment válido (um estado diferente de STA
(single-threaded apartment) ou MTA
(multithreaded apartment)).
Exemplos
O exemplo de código a seguir demonstra como definir o estado de apartment de um 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.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(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
A ApartmentState propriedade está obsoleta. As alternativas não obsoletas são o método para recuperar o estado do apartment e GetApartmentState o método para definir o estado do SetApartmentState apartment.
Nas .NET Framework versões 1.0 e 1.1, a propriedade marca um thread para indicar que ele será executado em um apartment de thread único ou ApartmentState
multithread. Essa propriedade pode ser definida quando o thread está no estado do thread ou ; no entanto, ela pode Unstarted
ser definida apenas uma vez para um Running
thread. Se a propriedade não tiver sido definida, ela retornará Unknown
.
Uma tentativa de usar a propriedade para definir o estado de apartment de um thread cujo estado de apartment já ApartmentState foi definido é ignorada. No entanto, SetApartmentState o método lança um nesse InvalidOperationException caso.
Importante
Na .NET Framework versão 2.0, novos threads são inicializados como se o estado do apartment não tivesse sido definido antes ApartmentState.MTA de eles iniciarem. O thread do aplicativo principal é inicializado ApartmentState.MTA como por padrão. Você não pode mais definir o thread do aplicativo principal como definindo a ApartmentState.STA propriedade na primeira linha de System.Threading.ApartmentState código. Em vez STAThreadAttribute disso, use o .
Na .NET Framework versão 2.0, você pode especificar o modelo de threading COM para um aplicativo C++ usando a opção de vinculador /CLRTHREADATTRIBUTE (Definir Atributo de Thread CLR).