0

I using the Parallel Task library to run async tasks in the background. Sometimes I have to wait that background task's completed delegate while the UI thread is non-blocked.

So:

  1. in UI thread start a spinner
  2. in background do some work that needs to be wait
  3. after that run another background task
  4. stop the spinner in the UI

I started the background task in the UI thread (2) after that I tried to call Wait method, which is cause a deadlock...

I need a solution to wait a specified background task without blocking the UI thread. .NET framework is 4 so I can't use async and await

Update:

In the UI thread:

Task task = Task.Factory.StartNew<T>(() => BackgroundTask());
task.ContinueWith(task => CompletedTask(((Task<T>)task).Result); // I want to prevent later tasks to start before this task is finished
task.Wait(); // this will block the ui...

Any advice appreciated.

hcpeter
  • 614
  • 3
  • 11
  • 24

1 Answers1

1

You use ContinueWith to attach a continuation to the task and run some code when the task finishes. await is doing effectively the same thing, behind the scenes.

You can use Task.Factory.ContinueWhenAll to run a continuation when all of a collection of tasks have finished.

You can use TaskScheduler.FromCurrentSynchronizationContext() from within the UI thread to get a task scheduler capable of scheduling tasks in the UI thread.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • Thank you for the answer, I tried it (maybe I made a mistake or didn't get the point) but it didn't worked. When I call the background task in the UI thread I set ContinueWith in the completed task. But later in the UI thread I start another task. And I want to wait to the first task is completed. That's why I try to use Wait. – hcpeter Mar 27 '14 at 13:51
  • @hcpeter please show what you tried as a edit to your question, we can help you correct your mistake then. – Scott Chamberlain Mar 27 '14 at 13:52
  • @hcpeter Store a reference to the task, and at some later point in time when you want to do something after that task has finished, add a continuation to it, instead of waiting on it. – Servy Mar 27 '14 at 14:01