Sets the apartment state of a thread before it is started.
Assembly: mscorlib (in mscorlib.dll)
[<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, SelfAffectingThreading = true)>] member TrySetApartmentState : state:ApartmentState -> bool
- Type: System.Threading.ApartmentState
The new apartment state.
Return ValueType: System.Boolean
true if the apartment state is set; otherwise, false.
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.
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 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.
The following code example demonstrates the GetApartmentState, SetApartmentState, and 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 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 method is used again. This time it throws ThreadStateException because the thread has already been started.
Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)