Thread.TrySetApartmentState Method (ApartmentState)

 
System_CAPS_noteNote

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

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

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

[<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true,
    SelfAffectingThreading = true)>]
member TrySetApartmentState : 
        state:ApartmentState -> bool

Parameters

state
Type: System.Threading.ApartmentState

The new apartment state.

Return Value

Type: System.Boolean

true if the apartment state is set; otherwise, false.

Exception Condition
ArgumentException

state is not a valid apartment state.

ThreadStateException

The thread has already been started.

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.

System_CAPS_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 TrySetApartmentState method, along with the GetApartmentState method and the SetApartmentState 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.

No code example is currently available or this language may not be supported.

.NET Framework
Available since 2.0
Return to top
Show: