Search code examples
c#windows-runtimewindows-phone-8.1async-awaitwinrt-async

Handling moment when async CoreDispatcher work completed or cancelled


For example, I need to use CoreDispatcher for refreshing MVVM properties in the UI Thread.

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...
}      

I am expect, then TaskInitializationCompleted handler will fire AFTER ScanAsync method completed, but it fire immediatly after Dispatcher.RunAsync method started and also BEFORE then ScanAsync was completed.

How I can check to really handle async Dispatcher work completed or cancelled?


Solution

  • Instead of registering to the Completed event, you can await RunAsync (Because DispatcherOperation is an awaitable) which will guarantee any code runs only after completion the invocations completion:

    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
    }