This documentation is archived and is not being maintained.

Thread.GetApartmentState Method

Returns an ApartmentState value indicating the apartment state.

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)

Public Function GetApartmentState As ApartmentState

Return Value

Type: System.Threading.ApartmentState
One of the ApartmentState values indicating the apartment state of the managed thread. The default is ApartmentState.Unknown.

This method, along with the SetApartmentState 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.

Imports System
Imports System.Threading

Module Example

    Sub Main()

        Dim t As New Thread(AddressOf ThreadProc)
        Console.WriteLine("Before setting apartment state: {0}", _

        Console.WriteLine("After setting apartment state: {0}", _

        Dim result As Boolean = _
        Console.WriteLine("Try to change state: {0}", result)



        Catch ex As ThreadStateException
            Console.WriteLine("ThreadStateException occurs " & _
                "if apartment state is set after starting thread.")
        End Try

    End Sub

    Sub ThreadProc()
    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.

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

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