Reputation: 1016
In a mobile application I have a potentially long async operation (multiple async network calls grouped in an async function).
_myClassField = myClient.DoANumberOfNetworkCallsAsync();
I execute the call right when the app starts, then I show the splash screen and the welcome screen and only at the first user interaction (e.g.: button press) I finally await on the task and make the user wait if the response is not ready.
public async Task<object> GetMyLongAwaitedObjectAsync()
{
return await _myClassField;
}
This method can be called multiple times and maybe from both UI and non UI threads.
Can this be a source of problems or it is a valid pattern?
Upvotes: 17
Views: 11948
Reputation: 14836
A completed task can be awaited as many times as you want and it will always yield the same result.
You can also call Wait()
or Result
as many times as you want and it won't block after the task is completed.
I would make on change to your code, though:
public Task<object> GetMyLongAwaitedObjectAsync()
{
return _myClassField;
}
This way, the compiler won't have to generate a state machine, and one won't be instantiated every time the property is invoked.
Upvotes: 21