Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Using Thread is pretty straightforward

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

How to accomplish the same using Tasks in a WPF application? Here is some code:

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

I'm getting an InvalidOperationException with

The calling thread must be STA, because many UI components require this.

like image 229
Michel Triana Avatar asked May 11 '11 23:05

Michel Triana


People also ask

Does Task run Use thread pool?

The main purpose of Task. Run() is to execute CPU-bound code in an asynchronous way. It does this by pulling a thread from the thread pool to run the method and returning a Task to represent the completion of the method.

Does Task create new thread?

A task can have multiple processes happening at the same time. Threads can only have one task running at a time. We can easily implement Asynchronous using 'async' and 'await' keywords. A new Thread()is not dealing with Thread pool thread, whereas Task does use thread pool thread.

What is the difference between a Task and a thread?

A task is something you want done. A thread is one of the many possible workers which performs that task. In . NET 4.0 terms, a Task represents an asynchronous operation.

How do you create a sta?

In the Configure STA Server dialog box, enter the URL of the STA server, click Create, and then click OK. In the STA Server dialog box, in URL, type the IP address or fully qualified domain name (FQDN) of the server running the STA and then click Create.


1 Answers

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); 
like image 118
dtb Avatar answered Nov 09 '22 02:11

dtb