Closed1

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

kenichiudakenichiuda

現在のスレッドアパートメント取得する

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を作成する。

https://devblogs.microsoft.com/pfxteam/parallelextensionsextras-tour-5-stataskscheduler/

https://github.com/dotnet/samples/blob/main/csharp/parallel/ParallelExtensionsExtras/TaskSchedulers/StaTaskScheduler.cs

WPF用のTaskScheduler

https://stackoverflow.com/a/10228693/15870569

    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にクローズされました