Partager via


Thread.SetApartmentState(ApartmentState) Méthode

Définition

Définit l'état de cloisonnement d'un thread avant qu'il ne soit démarré.

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)

Paramètres

state
ApartmentState

Nouvel état de cloisonnement.

Attributs

Exceptions

.NET Core et .NET 5 + uniquement : dans tous les cas sur macOS et Linux.

state n’est pas un état de cloisonnement valide.

Le thread a déjà été démarré.

L’état de cloisonnement a déjà été initialisé.

Exemples

L’exemple de code suivant illustre GetApartmentState les SetApartmentState méthodes, et TrySetApartmentState . L’exemple de code crée un thread. Avant le démarrage du thread, GetApartmentState affiche l' ApartmentState.Unknown état initial et SetApartmentState passe à l’état ApartmentState.STA . La TrySetApartmentState méthode retourne ensuite false lorsque la tentative de modification de l’état ApartmentState.MTA est définie sur car l’état de cloisonnement est déjà défini. Si la même opération a été tentée avec SetApartmentState , InvalidOperationException aurait été levé.

Une fois le thread démarré, la TrySetApartmentState méthode est réutilisée. Cette fois-ci, il lève une exception ThreadStateException car le thread a déjà été démarré.

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.

Remarques

Les nouveaux threads sont initialisés comme ApartmentState.MTA si leur état de cloisonnement n’avait pas été défini avant de démarrer. L’état de cloisonnement doit être défini avant le démarrage d’un thread.

Notes

Le thread d’application principal est initialisé ApartmentState.MTA par défaut. La seule façon de définir l’état de cloisonnement du thread d’application principal sur ApartmentState.STA consiste à appliquer l' STAThreadAttribute attribut à la méthode de point d’entrée.

La SetApartmentState méthode, ainsi que la méthode GetApartmentState et la TrySetApartmentState méthode, remplacent la ApartmentState propriété.

S’applique à