简体   繁体   English

在UI线程上分组多个异步操作

[英]Group multiple async operations on the UI thread

I have this: 我有这个:

BusyState.SetBusy("Updating Calendar Data");

Dispatcher.CurrentDispatcher.Invoke(new Action(async () =>
{
    // calling "update" will hit servers outside my control and may take time
    await PublicCalendars.Update();
    await PrivateCalendars.Update();

    // clearing the busy state should only happen when both update tasks are finished
    BusyState.ClearBusy();
}));

The vars PublicCalendars and PrivateCalendars are both extending ObservableCollection and are populated during the call to update. vars PublicCalendars和PrivateCalendars都扩展了ObservableCollection,并在调用更新期间填充。 The collections are bound to some WPF GUI so adding items must happen from the UI thread. 集合绑定到某些WPF GUI,因此添加项必须从UI线程进行。

I'd like to remove the await's and let both calls run simultaneously. 我想删除等待状态并让两个调用同时运行。 How can I do this and still have my busy state clear when both tasks are finished? 当两个任务都完成时,我该如何做却仍然清除忙碌状态?

The strength of Task s is that they can be easily composed. Task的优势在于可以轻松组成它们。 So, if you want to get a Task that represents the completion of both Task s, you can use a method that does that: Task.WhenAll() : 所以,如果你想获得一个Task ,代表双方的完成Task S,您可以使用这项作业的方法: Task.WhenAll()

await Task.WhenAny(PublicCalendars.Update(), PrivateCalendars.Update());

BusyState.ClearBusy();

And you could also get a very similar behavior by yourself by saving the returned Task s and then await ing them: 通过保存返回的Task然后 await它们,您也可以自己获得非常相似的行为:

var publicTask = PublicCalendars.Update();
var privateTask = PrivateCalendars.Update();

await publicTask;
await privateTask;

BusyState.ClearBusy();

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

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