Exception handling inside “async void” WPF command handlers

前端 未结 2 1612
无人共我
无人共我 2020-12-18 23:28

I\'m reviewing some WPF code of my colleagues, which is a library of UserControl-based components with a lot of async void

2条回答
  •  Happy的楠姐
    2020-12-18 23:55

    The propagation of exceptions about which the users are almost 100% unaware is not a good practice in my opinion. See this

    I see the two options you really have since WPF doesn't provide any out of the box mechanisms of such the notifying of any problems:

    1. The way you already offered with catching and firing the event.
    2. Return the Task object from the async method (in your case, it seems that you will have to expose it through the property). The users will be able to check if there were any errors during the execution and attach a continuation task if they want. Inside the handler you can catch any exceptions and use TaskCompletionSource to set the result of the handler.

    All in all you have to write some xml-comments for such a code, because that's not so easy to understand it. The most important thing is that you should never (almost) throw any exceptions from any secondary threads.

提交回复
热议问题