异步 CoreDispatcher 工作完成或取消时的处理时刻

Handling moment when async CoreDispatcher work completed or cancelled

例如,我需要使用 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 处理程序将在 ScanAsync 方法完成后触发,但它会在 [ 之后立即触发=25=] 方法已启动,并且在此之前 ScanAsync 已完成。

我如何才能真正处理完成或取消的异步调度程序工作?

您可以 await RunAsync(因为 DispatcherOperation 是可等待的)而不是注册到 Completed 事件,这将保证任何代码仅在调用完成后运行:

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
}