Thread.SetApartmentState(ApartmentState) Metodo

Definizione

Imposta lo stato dell'apartment di un thread prima che venga avviato.

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)

Parametri

state
ApartmentState

Nuovo stato dell'apartment.

Attributi

Eccezioni

Solo .NET Core e .NET 5+: in tutti i casi in macOS e Linux.

state non è uno stato di apartment valido.

Il thread è già stato avviato.

Lo stato di apartment è già stato inizializzato.

Esempio

Nell'esempio di codice seguente vengono illustrati i GetApartmentStatemetodi , SetApartmentStatee TrySetApartmentState . Nell'esempio di codice viene creato un thread. Prima dell'avvio del thread, GetApartmentState visualizza lo stato iniziale ApartmentState.Unknown e SetApartmentState lo stato viene modificato in ApartmentState.STA. Il TrySetApartmentState metodo restituisce false quindi quando si tenta di modificare lo stato in ApartmentState.MTA perché lo stato dell'apartment è già impostato. Se la stessa operazione fosse stata tentata con SetApartmentState, InvalidOperationException sarebbe stata generata.

Dopo l'avvio del thread, il TrySetApartmentState metodo viene nuovamente usato. Questa volta viene generata ThreadStateException perché il thread è già stato avviato.

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.
 */
open System.Threading

let threadProc () = Thread.Sleep 2000

let t = Thread threadProc
printfn $"Before setting apartment state: {t.GetApartmentState()}"

t.SetApartmentState ApartmentState.STA
printfn $"After setting apartment state: {t.GetApartmentState()}"

let result = t.TrySetApartmentState ApartmentState.MTA
printfn $"Try to change state: {result}"

t.Start()

Thread.Sleep 500

try
    t.TrySetApartmentState ApartmentState.STA |> ignore
with :? ThreadStateException ->
    printfn "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.
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.

Commenti

I nuovi thread vengono inizializzati come ApartmentState.MTA se il relativo stato apartment non sia stato impostato prima dell'avvio. Lo stato dell'apartment deve essere impostato prima dell'avvio di un thread.

Nota

Il thread dell'applicazione principale viene inizializzato in ApartmentState.MTA per impostazione predefinita. L'unico modo per impostare lo stato apartment del thread applicazione principale su ApartmentState.STA consiste nell'applicare l'attributo STAThreadAttribute al metodo del punto di ingresso.

Il SetApartmentState metodo, insieme al GetApartmentState metodo e al TrySetApartmentState metodo , sostituisce la ApartmentState proprietà .

Si applica a