Closed1
.NET でスレッドアパートメント(STA,MTAとか)をいじる時のメモ

現在のスレッドアパートメント取得する
var apartmentState = Thread.CurrentThread.GetApartmentState();
スレッドを作成してスレッドアパートメントを設定する
var thread = new Thread(() =>
{
// ...
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
非同期メインメソッドのスレッドアパートメントを設定する
[STAThread]
static void Main(string[] args)
{
AsyncMain(args).Wait();
}
static async Task AsyncMain(string[] args)
{
//...
}
STAで実行するTaskSchedulerを作成する。
WPF用のTaskScheduler
public class StaTaskSchedulerSource
{
private Window _window;
private readonly Thread _thread;
public TaskScheduler TaskScheduler { get; }
public StaTaskSchedulerSource()
{
using (var resetEvent = new ManualResetEventSlim(false))
{
this._thread = new Thread(
() =>
{
_window = new Window();
resetEvent.Set();
Dispatcher.Run();
})
{
IsBackground = true
};
this._thread.SetApartmentState(ApartmentState.STA);
this._thread.Start();
resetEvent.Wait();
}
TaskScheduler = this._window.Dispatcher.Invoke(static () => TaskScheduler.FromCurrentSynchronizationContext());
}
}
このスクラップは2021/07/12にクローズされました