简体   繁体   中英

Parallel Task Wait from UI without blocking

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM