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?
In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise.
In . NET, Task. Run is used to asynchronously execute CPU-bound code.
If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. By default, this message is a warning.
If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread. If it is unable to do that, or if the current task has already started execution, it blocks the calling thread until the task completes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With