例如,我需要使用CoreDispatcher在UI线程中刷新MVVM属性。
private void ButtonClick(object sender, RoutedEventArgs e)
{
//Code not compile without keyword async
var dispatcherResult = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
//This method contains awaitable code
await _scanner.ScanAsync();
}
);
dispatcherResult.Completed = new AsyncActionCompletedHandler(TaskInitializationCompleted);
}
private void TaskInitializationCompleted (IAsyncAction action, AsyncStatus status )
{
//Do something...
}
我希望,然后 TaskInitializationCompleted 处理程序将在AFTER ScanAsync 方法完成后触发,但它在 Dispatcher.RunAsync 方法启动后立即触发之前 ScanAsync 已完成。
如何检查以真正处理完成或取消异步Dispatcher工作?
答案 0 :(得分:2)
您可以Completed
(因为await RunAsync
是等待的)而不是注册DispatcherOperation
事件,这将保证任何代码仅在完成调用完成后运行:
private async void ButtonClick(object sender, RoutedEventArgs e)
{
var dispatcherResult = await this.Dispatcher
.RunAsync(CoreDispatcherPriority.Normal,
async () =>
{
await _scanner.ScanAsync();
});
// Do something after `RunAsync` completed
}