Thread.TrySetApartmentState(ApartmentState) Metodo

Definizione

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

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

Parametri

state
ApartmentState

Nuovo stato dell'apartment.

Restituisce

Boolean

true se è impostato lo stato dell'apartment; in caso contrario, false.

Eccezioni

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

state non è uno stato di apartment valido.

Il thread è stato avviato e completato o la chiamata non viene eseguita dal contesto del thread mentre il thread è in esecuzione.

Esempio

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

Dopo l'avvio del thread, il TrySetApartmentState metodo viene usato nuovamente. Questa volta viene generata ThreadStateException un'eccezione 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.
 */
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 se il relativo stato apartment non ApartmentState.MTA fosse stato impostato prima dell'avvio. Lo stato dell'apartment deve essere impostato prima dell'avvio di un thread.

Nota

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

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

Si applica a