How to use await in event handlers
You are writing some code and you find yourself needing to call an async method in your event handler. The event handler, obviously, has a void return type and is not async, so when using await in it, you will get a compile error. I actually had a special class to execute async method synchronously and I used that one, but I didn't actually need it.
The solution is extremely simple: just mark the event handler as async.
You should never use async void methods, instead use async Task or async Task<T1,...>. The exception, apparently, is event handlers. And it kind of makes sense: an event handler is designed to be called asynchronously.
More details here: Tip 1: Async void is for top-level event-handlers only
And bonus: but what about constructors? They can't be marked as async, they have no return type!
First, why are you executing code in your constructor? And second, if you absolutely must, you can also create an async void method that you call from the constructor. But the best solution is to make the constructor private and instead use a static async method to create the class, which will execute whatever code you need and then return new YourClass(values returned from async methods).
That's a very good pattern, regardless of asynchronous methods: if you need to execute code in the constructor, consider hiding it and using a creation method instead.
Comments
What a waste. Since the event handler is declared outside of Main, you can't use it as an await reference.
Roscoe SandstoneThank you for your post. Very helpful :)
Rahul