Significance of declaring a WPF event handler as 'async' in C# 5

后端 未结 2 1636
深忆病人
深忆病人 2021-02-12 14:57

Imagine a WPF code-behind event handler:

In C# 4 you would declare your handler as:

pr         


        
2条回答
  •  渐次进展
    2021-02-12 15:34

    You may find my async/await intro helpful.

    An async method is re-written by the compiler to support the await operator. Every async method starts out synchronous (in this case, on the UI thread) until it awaits 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.Current unless it is null, in which case it is TaskScheduler.Current. As Drew pointed out, WPF provides a DispatcherSynchronizationContext which is tied to the WPF Dispatcher.

    Regarding error handling:

    When you await a Task inside a WPF async void event handler, the error handling goes like this:

    • The Task completes with an error. The exception is wrapped into an AggregateException, like all Task errors.
    • The await operator sees that the Task completed with an error. It unwraps the original exception and re-throws it, preserving the original stack trace.
    • The async void method builder catches the exception escaping from an async void method and passes it to the SynchronizationContext that was active when the async void method started executing (in this case, the same WPF context).
    • The exception is raised (with the original stack trace, and without any annoying AggregateException wrapping) on the Dispatcher.

    This is rather convoluted, but the intent is to have exceptions raised from async event handlers be practically the same as exceptions raised from regular event handlers.

提交回复
热议问题