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.
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With