I noticed that yesterday, someone read my post on Cancellation after searching the web to find out how to call async methods from properties. I am no expert on async code; I’ve just been playing with it for a while – since the 2nd Async CTP, but since I’ve never seen a post on this from my favourite author of async code articles, here are my thoughts on this.
You can’t mark either a property, nor it’s get/set assessors as async. I assume that’s the issue the person had. They can’t use the await keyword, because they can’t mark the code as async.
While I don’t know the Microsoft developer teams’ reasons for implementing it this way, I can guess: When a developer gets or sets a property, they expect it to be synchronous. It’s not the sort of place where anyone expects the code to go away to the netherworld, and return sometime in the future.
That said, there are async methods that you can call, but in the same context as event handlers, they need to be async void methods. That is, fire-and-forget async methods, not the type where you wait asynchronously for something to happen. And if you really… really.. have to use the await keyword in a property, or any other method that isn’t marked as async, you can, by putting it inside a lambda expression, but that’s really exactly the same as calling an async void method.
I’ve written a little console application to demonstrate:
The demo program has a class with two properties, Awesome and Awesome1.
When the Awesome property is set, it calls an async void method. When the Awesome1 property is set, it calls an async lambda. If you run the demo program, you should get output something like this:
As you can see, whether you call an async void method or a lambda expression, the code returns execution from the property setter immediately, while the async code continues to run in the background.