Microsoft Documentation
Specifies the COM threading model for a thread. Apartment states are relevant for COM interop.
When you create a Thread object, you can specify the apartment state in the ApartmentState enumeration. The default value for managed threads is MTA.
The apartment state of a thread affects how COM components interact with that thread.
You can set the apartment state of a thread using the ApartmentState property of the Thread class. Note that setting the apartment state must be done before the thread starts execution.
using System;
using System.Threading;
public class ApartmentStateExample
{
public static void Main()
{
// Create a new thread and set its apartment state to STA
Thread thread = new Thread(new ThreadStart(DoWork));
thread.SetApartmentState(ApartmentState.STA);
// Start the thread
thread.Start();
// Wait for the thread to complete
thread.Join();
// Get and display the apartment state of the current thread
Console.WriteLine($"Current thread apartment state: {Thread.CurrentThread.ApartmentState}");
// Get and display the apartment state of the created thread
Console.WriteLine($"Created thread apartment state: {thread.ApartmentState}");
}
public static void DoWork()
{
Console.WriteLine($"Worker thread started with apartment state: {Thread.CurrentThread.ApartmentState}");
// Perform some work here...
}
}