How to create a task (TPL) running a STA thread? How to create a task (TPL) running a STA thread? multithreading multithreading

How to create a task (TPL) running a STA thread?


You can use the TaskScheduler.FromCurrentSynchronizationContext Method to get a TaskScheduler for the current synchronization context (which is the WPF dispatcher when you're running a WPF application).

Then use the ContinueWith overload that accepts a TaskScheduler:

var scheduler = TaskScheduler.FromCurrentSynchronizationContext();Task.Factory.StartNew(...)            .ContinueWith(r => AddControlsToGrid(r.Result), scheduler);


Dispatcher.Invoke could be a solution. e.g.

    private async Task<bool> MyActionAsync()    {        // await for something, then return true or false    }    private void StaContinuation(Task<bool> t)    {        myCheckBox.IsChecked = t.Result;    }    private void MyCaller()    {        MyActionAsync().ContinueWith((t) => Dispatcher.Invoke(() => StaContinuation(t)));    }