Thread.SetApartmentState(ApartmentState) Método

Definición

Establece el estado del apartamento de un subproceso antes de iniciarse.

public:
 void SetApartmentState(System::Threading::ApartmentState state);
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public void SetApartmentState (System.Threading.ApartmentState state);
public void SetApartmentState (System.Threading.ApartmentState state);
[<System.Runtime.Versioning.SupportedOSPlatform("windows")>]
member this.SetApartmentState : System.Threading.ApartmentState -> unit
member this.SetApartmentState : System.Threading.ApartmentState -> unit
Public Sub SetApartmentState (state As ApartmentState)

Parámetros

state
ApartmentState

Nuevo estado del apartamento.

Atributos

Excepciones

Solo .NET Core y .NET 5+: en todos los casos en macOS y Linux.

state no es un estado del apartamento válido.

Ya se inició el subproceso.

El estado de apartamento ya se inicializó.

Ejemplos

En el ejemplo de código siguiente se muestran GetApartmentState los métodos SetApartmentState , y TrySetApartmentState . En el ejemplo de código se crea un subproceso. Antes de iniciar el subproceso, GetApartmentState muestra el estado inicial y cambia el estado a ApartmentState.Unknown SetApartmentState ApartmentState.STA . A TrySetApartmentState continuación, el método devuelve cuando se intenta cambiar el estado a porque el estado del apartamento false ya está ApartmentState.MTA establecido. Si se hubiera intentado la misma operación con SetApartmentState , se habría producida InvalidOperationException .

Una vez iniciado el subproceso, se TrySetApartmentState vuelve a usar el método . Esta vez se produce porque ThreadStateException el subproceso ya se ha iniciado.

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.

Comentarios

Los subprocesos nuevos se inicializan ApartmentState.MTA como si su estado de apartamento no se hubiera establecido antes de iniciarse. El estado del apartamento debe establecerse antes de iniciar un subproceso.

Nota

El subproceso de aplicación principal se inicializa en ApartmentState.MTA de forma predeterminada. La única manera de establecer el estado de apartamento del subproceso de aplicación principal en ApartmentState.STA es aplicar el atributo al método de punto de STAThreadAttribute entrada.

El SetApartmentState método, junto con GetApartmentState el método y el método , reemplaza la propiedad TrySetApartmentState ApartmentState .

Se aplica a