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
}
}
You can change the proerty to
Task<IEnumerable>
and do something like:
and use it like await MyList;
I think that we can await for the value just returning first null and then get the real value, so in the case of Pure MVVM (PCL project for instance) I think the following is the most elegant solution:
One thing to note: In the case where an IEnumerable result is returned yield return is has better performance and does not require conversion to IEnumerable.
Since your "async property" is in a viewmodel, you could use AsyncMVVM:
It will take care of the synchronization context and property change notification for you.
You can't call it asynchronously, since there is no asynchronous property support, only async methods. As such, there are two options, both taking advantage of the fact that asynchronous methods in the CTP are really just a method that returns
Task<T>
orTask
:Or:
I thought .GetAwaiter().GetResult() was exactly the solution to this problem, no? eg: