Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
Thread Class
Thread Methods
 SetApartmentState Method
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
Thread..::.SetApartmentState Method

Sets the apartment state of a thread before it is started.

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic (Declaration)
<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True,  _
    SelfAffectingThreading := True)> _
Public Sub SetApartmentState ( _
    state As ApartmentState _
)
Visual Basic (Usage)
Dim instance As Thread
Dim state As ApartmentState

instance.SetApartmentState(state)
C#
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
    SelfAffectingThreading = true)]
public void SetApartmentState(
    ApartmentState state
)
Visual C++
[HostProtectionAttribute(SecurityAction::LinkDemand, Synchronization = true, 
    SelfAffectingThreading = true)]
public:
void SetApartmentState(
    ApartmentState state
)
JScript
public function SetApartmentState(
    state : ApartmentState
)

Parameters

state
Type: System.Threading..::.ApartmentState
The new apartment state.
ExceptionCondition
ArgumentException

state is not a valid apartment state.

ThreadStateException

The thread has already been started.

InvalidOperationException

The apartment state has already been initialized.

NoteNote:

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | SelfAffectingThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

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.

NoteNote:

The main application thread is initialized to ApartmentState..::.MTA by default. 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.

The SetApartmentState method, along with the GetApartmentState method and the TrySetApartmentState method, replaces the ApartmentState property.

The following code example demonstrates the GetApartmentState, SetApartmentState, and TrySetApartmentState methods. The code example creates a thread. Before the thread is started, GetApartmentState displays the initial ApartmentState..::.Unknown state and SetApartmentState changes the state to ApartmentState..::.STA. The TrySetApartmentState method then returns false when attempting to change the state to ApartmentState..::.MTA because the apartment state is already set. If the same operation had been attempted with SetApartmentState, InvalidOperationException would have been thrown.

After the thread is started, the TrySetApartmentState method is used again. This time it throws ThreadStateException because the thread has already been started.

Visual Basic
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.
C#
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.
 */
Visual C++
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.
 */

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker