How to create a task (TPL) using an STA thread?

Using Thread is pretty simple

Thread thread = new Thread(MethodWhichRequiresSTA); thread.SetApartmentState(ApartmentState.STA); 

How to do the same using tasks in a WPF application? Here is the code:

 Task.Factory.StartNew ( () => {return "some Text";} ) .ContinueWith(r => AddControlsToGrid(r.Result)); 

I get an InvalidOperationException with

The calling thread must be an STA because it requires many user interface components.

+60
multithreading c # thread-safety wpf task-parallel-library
May 11 '11 at 23:24
source share
2 answers

You can use the TaskScheduler.FromCurrentSynchronizationContext Method to get the TaskScheduler for the current synchronization context (which is the WPF manager when the WPF application starts).

Then use ContinueWith the overload that accepts the TaskScheduler:

 var scheduler = TaskScheduler.FromCurrentSynchronizationContext(); Task.Factory.StartNew(...) .ContinueWith(r => AddControlsToGrid(r.Result), scheduler); 
+65
May 11 '11 at 23:31
source share

For any future visitors who are looking for the real purpose of the question:

  • Using StaTaskScheduler as indicated in the answer
  • DIY Version: Install ApartmentState in the Task
+22
Apr 21 '14 at 20:00
source share



All Articles