Thread.SetApartmentState(ApartmentState) Thread.SetApartmentState(ApartmentState) Thread.SetApartmentState(ApartmentState) Thread.SetApartmentState(ApartmentState) Method

Определение

Задает модель "apartment" для потока до его запуска.Sets the apartment state of a thread before it is started.

public:
 void SetApartmentState(System::Threading::ApartmentState state);
public void SetApartmentState (System.Threading.ApartmentState state);
member this.SetApartmentState : System.Threading.ApartmentState -> unit
Public Sub SetApartmentState (state As ApartmentState)

Параметры

state
ApartmentState ApartmentState ApartmentState ApartmentState

Новая модель "apartment".The new apartment state.

Исключения

Только в .NET Core: этот элемент не поддерживается на платформах Linux и macOS..NET Core only: This member is not supported on the macOS and Linux platforms.

state не является допустимым состоянием подразделения.state is not a valid apartment state.

Поток уже запущен.The thread has already been started.

Состояние подразделения уже инициализировано.The apartment state has already been initialized.

Примеры

В следующем примере кода демонстрируются GetApartmentStateметоды SetApartmentState, и TrySetApartmentState .The following code example demonstrates the GetApartmentState, SetApartmentState, and TrySetApartmentState methods. В примере кода создается поток.The code example creates a thread. Перед запуском GetApartmentState потока отображает начальное ApartmentState.Unknown состояние и SetApartmentState изменяет состояние на ApartmentState.STA.Before the thread is started, GetApartmentState displays the initial ApartmentState.Unknown state and SetApartmentState changes the state to ApartmentState.STA. Затем метод возвращается false при попытке изменить состояние на ApartmentState.MTA , так как состояние апартамента уже задано. TrySetApartmentStateThe TrySetApartmentState method then returns false when attempting to change the state to ApartmentState.MTA because the apartment state is already set. Если одна и та же операция была предпринята InvalidOperationException с помощью SetApartmentState, было бы создано исключение.If the same operation had been attempted with SetApartmentState, InvalidOperationException would have been thrown.

После запуска TrySetApartmentState потока метод используется снова.After the thread is started, the TrySetApartmentState method is used again. В этот раз возникает ThreadStateException исключение, поскольку поток уже запущен.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
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.

Комментарии

Новые потоки инициализируются так, ApartmentState.MTA как если бы их состояние апартамента не было задано до запуска.New threads are initialized as ApartmentState.MTA if their apartment state has not been set before they are started. Перед запуском потока необходимо задать состояние апартамента.Apartment state must be set before a thread is started.

Примечание

Основной поток приложения инициализируется ApartmentState.MTA значением по умолчанию.The main application thread is initialized to ApartmentState.MTA by default. Единственный способ задать для состояния подразделения основного потока ApartmentState.STA приложения значение — STAThreadAttribute применить атрибут к методу точки входа.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.

Метод, вместе GetApartmentState с методом и TrySetApartmentState методом, заменяет ApartmentState свойство. SetApartmentStateThe SetApartmentState method, along with the GetApartmentState method and the TrySetApartmentState method, replaces the ApartmentState property.

Применяется к