简体   繁体   中英

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. The collections are bound to some WPF GUI so adding items must happen from the UI thread.

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. 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() :

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:

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

await publicTask;
await privateTask;

BusyState.ClearBusy();

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