![](/img/trans.png)
[英]Use async/await on synchronous operations (mainly to stay on UI thread)
[英]Group multiple async operations on the UI thread
我有这个:
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();
}));
vars PublicCalendars和PrivateCalendars都扩展了ObservableCollection,并在调用更新期间填充。 集合绑定到某些WPF GUI,因此添加项必须从UI线程进行。
我想删除等待状态并让两个调用同时运行。 当两个任务都完成时,我该如何做却仍然清除忙碌状态?
Task
的优势在于可以轻松组成它们。 所以,如果你想获得一个Task
,代表双方的完成Task
S,您可以使用这项作业的方法: Task.WhenAll()
await Task.WhenAny(PublicCalendars.Update(), PrivateCalendars.Update());
BusyState.ClearBusy();
通过保存返回的Task
, 然后 await
它们,您也可以自己获得非常相似的行为:
var publicTask = PublicCalendars.Update();
var privateTask = PrivateCalendars.Update();
await publicTask;
await privateTask;
BusyState.ClearBusy();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.