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

后端 未结 2 1398
萌比男神i
萌比男神i 2021-02-12 14:55

Imagine a WPF code-behind event handler:

In C# 4 you would declare your handler as:

pr         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-12 15:41

    A partial answer. From MSDN:

    An async method that has a void return type can’t be awaited, and the caller of a void-returning method can't catch any exceptions that the method throws.

    So any errors would only be available via the TaskScheduler.

    Also, there's nothing XAML-specific going on with the event handler registration. It could have been done in code:

    this.button.Click += OnButtonClick;
    

    Or even as an async lambda:

    this.button.Click += async (s,e) => { ... };
    

    As for safety of UI updates after an await, it seems that the continuation is executed within SynchronisationContext.Current, which is set per thread. In WPF, this is a DispatcherSynchronisationContext that's coupled to the WPF Dispatcher that pumped the event in the first place.

提交回复
热议问题