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

时间:2014-03-27 13:44:57

标签: c# asynchronous task-parallel-library

我使用Parallel Task库在后台运行异步任务。有时我必须等待后台任务完成的委托,而UI线程没有被阻止。

所以:

    UI线程中的
  1. 启动一个微调器
  2. 在后台做一些需要等待的工作
  3. 之后运行另一个后台任务
  4. 在UI中停止微调器
  5. 我在UI线程(2)中启动了后台任务,之后我尝试调用Wait方法,这导致死锁......

    我需要一个解决方案来等待指定的后台任务而不会阻止UI线程。 .NET框架是4,因此我无法使用asyncawait

    更新

    在UI线程中:

    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...
    

    任何建议表示赞赏。

1 个答案:

答案 0 :(得分:1)

使用ContinueWith附加任务的延续并在任务完成时运行一些代码。 await在幕后做了同样的事情。

当所有任务集合完成后,您可以使用Task.Factory.ContinueWhenAll运行延续。

您可以在UI线程中使用TaskScheduler.FromCurrentSynchronizationContext()来获取能够在UI线程中安排任务的任务调度程序。