Thread.TrySetApartmentState(ApartmentState) Método

Definição

Define o estado do apartment de um thread antes que ele seja iniciado.Sets the apartment state of a thread before it is started.

public:
 bool TrySetApartmentState(System::Threading::ApartmentState state);
public bool TrySetApartmentState (System.Threading.ApartmentState state);
member this.TrySetApartmentState : System.Threading.ApartmentState -> bool
Public Function TrySetApartmentState (state As ApartmentState) As Boolean

Parâmetros

state
ApartmentState

O novo estado de apartment.The new apartment state.

Retornos

true se o estado de apartment for definido; caso contrário, false.true if the apartment state is set; otherwise, false.

Exceções

Somente .NET Core: esse membro não é compatível com as plataformas macOS e Linux..NET Core only: This member is not supported on the macOS and Linux platforms.

state não é um estado de apartment válido.state is not a valid apartment state.

O thread foi iniciado e encerrado ou a chamada não está sendo realizada do contexto do thread enquanto ele está em execução.The thread was started and has terminated, or the call is not being made from the thread's context while the thread is running.

Exemplos

O exemplo de código a seguir demonstra os métodos GetApartmentState, SetApartmentState e TrySetApartmentState.The following code example demonstrates the GetApartmentState, SetApartmentState, and TrySetApartmentState methods. O exemplo de código cria um thread.The code example creates a thread. Antes de o thread ser iniciado, GetApartmentState exibe o estado de ApartmentState.Unknown inicial e SetApartmentState altera o estado para ApartmentState.STA.Before the thread is started, GetApartmentState displays the initial ApartmentState.Unknown state and SetApartmentState changes the state to ApartmentState.STA. Em seguida, o método TrySetApartmentState retorna false ao tentar alterar o estado para ApartmentState.MTA porque o estado de apartamento já está definido.The TrySetApartmentState method then returns false when attempting to change the state to ApartmentState.MTA because the apartment state is already set. Se a mesma operação tiver sido tentada com SetApartmentState, InvalidOperationException teria sido lançada.If the same operation had been attempted with SetApartmentState, InvalidOperationException would have been thrown.

Depois que o thread é iniciado, o método TrySetApartmentState é usado novamente.After the thread is started, the TrySetApartmentState method is used again. Desta vez, ele gera ThreadStateException porque o thread já foi iniciado.This time it throws ThreadStateException because the thread has already been started.

using namespace System;
using namespace System::Threading;

void ThreadProc()
{
    Thread::Sleep(2000);
};

void main()
{
    Thread^ t = gcnew Thread(gcnew ThreadStart(ThreadProc));
    Console::WriteLine("Before setting apartment state: {0}", 
            t->GetApartmentState());

    t->SetApartmentState(ApartmentState::STA);
    Console::WriteLine("After setting apartment state: {0}", 
        t->GetApartmentState());

    bool result = t->TrySetApartmentState(ApartmentState::MTA);
    Console::WriteLine("Try to change state: {0}", result);

    t->Start();

    Thread::Sleep(500);

    try
    {
        t->TrySetApartmentState(ApartmentState::STA);
    }
    catch (ThreadStateException^)
    {
        Console::WriteLine("ThreadStateException occurs " +
            "if apartment state is set after starting thread.");
    }

    t->Join();
}

/* This code example produces the following output:

Before setting apartment state: Unknown
After setting apartment state: STA
Try to change state: False
ThreadStateException occurs if apartment state is set after starting thread.
 */
using System;
using System.Threading;

class Example
{
    public static void Main()
    {
        Thread t = new Thread(ThreadProc);
        Console.WriteLine("Before setting apartment state: {0}", 
            t.GetApartmentState());

        t.SetApartmentState(ApartmentState.STA);
        Console.WriteLine("After setting apartment state: {0}", 
            t.GetApartmentState());

        bool result = t.TrySetApartmentState(ApartmentState.MTA);
        Console.WriteLine("Try to change state: {0}", result);

        t.Start();

        Thread.Sleep(500);

        try
        {
            t.TrySetApartmentState(ApartmentState.STA);
        }
        catch (ThreadStateException)
        {
            Console.WriteLine("ThreadStateException occurs " +
                "if apartment state is set after starting thread.");
        }

        t.Join();
    }

    public static void ThreadProc()
    {
        Thread.Sleep(2000);
    }
}

/* This code example produces the following output:

Before setting apartment state: Unknown
After setting apartment state: STA
Try to change state: False
ThreadStateException occurs if apartment state is set after starting thread.
 */
Imports System.Threading

Module Example

    Sub Main()
 
        Dim t As New Thread(AddressOf ThreadProc)
        Console.WriteLine("Before setting apartment state: {0}", _
            t.GetApartmentState())

        t.SetApartmentState(ApartmentState.STA)
        Console.WriteLine("After setting apartment state: {0}", _
            t.GetApartmentState())

        Dim result As Boolean = _
            t.TrySetApartmentState(ApartmentState.MTA)
        Console.WriteLine("Try to change state: {0}", result)

        t.Start()

        Thread.Sleep(500)

        Try
            t.TrySetApartmentState(ApartmentState.STA)
        Catch ex As ThreadStateException
            Console.WriteLine("ThreadStateException occurs " & _
                "if apartment state is set after starting thread.")
        End Try

        t.Join()
    End Sub

    Sub ThreadProc()
        Thread.Sleep(2000)
    End Sub
End Module

' This code example produces the following output:
'
'Before setting apartment state: Unknown
'After setting apartment state: STA
'Try to change state: False
'ThreadStateException occurs if apartment state is set after starting thread.

Comentários

Novos threads são inicializados como ApartmentState.MTA se o estado de seu apartamento não tiver sido definido antes de serem iniciados.New threads are initialized as ApartmentState.MTA if their apartment state has not been set before they are started. O estado do apartamento deve ser definido antes do início de um thread.Apartment state must be set before a thread is started.

Observação

O thread do aplicativo principal é inicializado para ApartmentState.MTA por padrão.The main application thread is initialized to ApartmentState.MTA by default. A única maneira de definir o estado de apartamento do thread do aplicativo principal como ApartmentState.STA é aplicar o atributo STAThreadAttribute ao método de ponto de entrada.The only way to set the apartment state of the main application thread to ApartmentState.STA is to apply the STAThreadAttribute attribute to the entry point method.

O método TrySetApartmentState, juntamente com o método GetApartmentState e o método SetApartmentState, substitui a propriedade ApartmentState.The TrySetApartmentState method, along with the GetApartmentState method and the SetApartmentState method, replaces the ApartmentState property.

Aplica-se a