Imagine a WPF code-behind event handler:
<Button Click="OnButtonClick" />
In C# 4 you would declare your handler as:
private void OnButtonClick(object sender, RoutedEventArgs e) { ... }
In C# 5 you can declare an async handler
private async void OnButtonClick(object sender, RoutedEventArgs e) { ... }
So what is WPF doing with this? A few minutes of searching about didn’t turn anything up.
It seems that it’s possible to perform UI updates after await statements. Does this imply that the task is continued on the Dispatcher thread?
If the Task raised an error, would it be raised through the WPF Dispatcher, or only via the TaskScheduler?
Are there any other interesting aspects to this that might be nice to understand?
You may find my async/await intro helpful.
An
asyncmethod is re-written by the compiler to support theawaitoperator. Everyasyncmethod starts out synchronous (in this case, on the UI thread) until itawaits some operation (that is not already completed).By default, the context is saved, and when the operation completes, the rest of the method is scheduled to execute in that context. The “context” here is
SynchronizationContext.Currentunless it isnull, in which case it isTaskScheduler.Current. As Drew pointed out, WPF provides aDispatcherSynchronizationContextwhich is tied to the WPFDispatcher.Regarding error handling:
When you
awaitaTaskinside a WPFasync voidevent handler, the error handling goes like this:Taskcompletes with an error. The exception is wrapped into anAggregateException, like allTaskerrors.awaitoperator sees that theTaskcompleted with an error. It unwraps the original exception and re-throws it, preserving the original stack trace.async voidmethod builder catches the exception escaping from anasync voidmethod and passes it to theSynchronizationContextthat was active when theasync voidmethod started executing (in this case, the same WPF context).AggregateExceptionwrapping) on theDispatcher.This is rather convoluted, but the intent is to have exceptions raised from
asyncevent handlers be practically the same as exceptions raised from regular event handlers.