简体   繁体   English

从UI进行并行任务等待而不会阻塞

[英]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. 有时,当UI线程未阻塞时,我必须等待该后台任务的完成委托。

So: 所以:

  1. in UI thread start a spinner 在UI线程中启动微调器
  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... 在尝试调用Wait方法之后,我在UI线程(2)中启动了后台任务,这导致死锁...

I need a solution to wait a specified background task without blocking the UI thread. 我需要一个解决方案来等待指定的后台任务,而又不会阻塞UI线程。 .NET framework is 4 so I can't use async and await .NET Framework是4,所以我不能使用asyncawait

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. 您可以使用ContinueWith将延续附加到任务,并在任务完成时运行一些代码。 await is doing effectively the same thing, behind the scenes. 在幕后, await实际上是在做同样的事情。

You can use Task.Factory.ContinueWhenAll to run a continuation when all of a collection of tasks have finished. 当所有任务集合都完成后,可以使用Task.Factory.ContinueWhenAll运行延续。

You can use TaskScheduler.FromCurrentSynchronizationContext() from within the UI thread to get a task scheduler capable of scheduling tasks in the UI thread. 您可以从UI线程中使用TaskScheduler.FromCurrentSynchronizationContext()获得能够在UI线程中调度任务的任务调度程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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