Tip 1: Async void is for top-level event-handlers only
- Posted: Mar 12, 2013 at 6:00AM
- 55,533 views
- 8 comments
Loading user information from Channel 9
Something went wrong getting user information from Channel 9
Loading user information from MSDN
Something went wrong getting user information from MSDN
Loading Visual Studio Achievements
Something went wrong getting the Visual Studio Achievements
Right click “Save as…”
Async Tip #1: Async void is for top-level event-handlers only, and event-like things. Don't use it elsewhere in your code.
Slides are available on Lucian's blog.
Async void is a "fire-and-forget" mechanism: the caller is unable to know when an async void has finished, and the caller is unable to catch any exceptions from it. The only case where this kind of fire-and-forget is appropriate is in top-level event-handlers. Every other async method in your code should return "async Task".
This video goes into some more difficult cases like the Win8 example "overrides async void LoadSettings()". Here you're overriding the method, and can't change the signature, and can't return a Task from it. The solution is to return a Task some other way, like through a field.
The video also talks about the thorny problem of async void lambdas. WHENEVER you see an async lambda, you need to verify whether it will be a void-returning or Task-returning lambda.