等待多个任务显示在GUI中 [英] Await multiple tasks to be shown in GUI

查看:68
本文介绍了等待多个任务显示在GUI中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个资源AB,我都想通过MVVM(此==视图模型)向用户展示这两个资源

Suppose I have two resources A and B, both of which I want to show to my user, via MVVM (this == view model)

this.A = GetA();
this.B = GetB();

我开始使用TPL:

this.A = await GetAAsync();
this.B = await GetBAsync();

这开始得到A.准备好A时,它会显示A并继续对B做同样的事情-这不是一个很好的解决方案.会更好:

This starts to get A. When A is ready, it shows A and proceeds to do the same with B -- not a very good solution. Would be better to:

var taskA = GetAAsync();
var taskB = GetBAsync();
this.A = await taskA;
this.B = await taskB;

现在,这开始获取A,开始获取B并等待A.当A准备就绪时,它会显示A并等待B,直到同样显示. 看起来不错,但是,如果A有时需要比B多得多的时间来加载,怎么办?

Now, this starts to get A, starts to get B and waits for A. When A is ready, it shows A and waits for B, until it is shown, too. Looks good, but, what if A sometimes takes much more time to load, than B?

如何实现以下方案:

  • 开始加载A.
  • 开始加载B.
  • 其中一个准备好后,显示出来.
  • 当另一个准备好时,也显示它.
  • Start loading A.
  • Start loading B.
  • When one of them is ready, show it.
  • When the other one is ready, show it, too.

推荐答案

您可以分别安排对这两个任务的继续.

You can schedule continuations on those two tasks separately.

var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
GetAAsync().ContinueWith(t => this.A = t.Result, uiScheduler);
GetBAsync().ContinueWith(t => this.B = t.Result, uiScheduler);

这样,如果这是WinForms或WPF应用程序,则继续将为您分派到UI线程.

This way, if this is a WinForms or WPF app, the continuations will be dispatched to the UI thread for you.

还要注意,我没有为调用线程编写任何代码来等待这两个任务完成.如果您要阻止调用线程(不建议使用)并且该线程恰好是UI线程,那么您将遇到死锁情况:

Also note that I didn't write any code for the calling thread to wait for those two tasks to be completed. If you were to block the calling thread (not recommended) and that thread happens to be the UI thread, then you will run into a dead-lock situation:

var taskA = GetAAsync().ContinueWith(t => this.A = t.Result, uiScheduler);
var taskB = GetBAsync().ContinueWith(t => this.B = t.Result, uiScheduler);
Task.WaitAll(taskA, taskB); 

最后一行将阻止UI线程.而且,当任务尝试在UI线程(已阻止)上分派继续执行时,这将阻止任务完成.

The last line will block the UI thread. And when the tasks try to dispatch the continuations on the UI thread (which is blocked), this will prevent the tasks from being completed.

这篇关于等待多个任务显示在GUI中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆