What'd be the most elegant way to call an async method from a getter or setter in C#?
Here's some pseudo-code to help explain myself.
async Task<IEnumerable> MyAsyncMethod()
{
return await DoSomethingAsync();
}
public IEnumerable MyList
{
get
{
//call MyAsyncMethod() here
}
}
There is no technical reason that
async
properties are not allowed in C#. It was a purposeful design decision, because "asynchronous properties" is an oxymoron.Properties should return current values; they should not be kicking off background operations.
Usually, when someone wants an "asynchronous property", what they really want is one of these:
async
method.async
factory method for the containing object or use anasync InitAsync()
method. The data-bound value will bedefault(T)
until the value is calculated/retrieved.AsyncLazy
from my blog or AsyncEx library. This will give you anawait
able property.Update: I cover asynchronous properties in one of my recent "async OOP" blog posts.
I really needed the call to originate from the get method, due to my decoupled architecture. So I came up with the following implementation.
Usage: Title is in a ViewModel or an object you could statically declare as a page resource. Bind to it and the value will get populated without blocking the UI, when getTitle() returns.