Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start a Task and await later and multiple times

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?

like image 551
Pinco Pallino Avatar asked Dec 02 '15 00:12

Pinco Pallino


People also ask

Can you have multiple awaits?

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.

Is Task run asynchronous?

In . NET, Task. Run is used to asynchronously execute CPU-bound code.

What happens if you dont await a Task?

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.

Does Task wait block?

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.


1 Answers

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.

like image 116
Paulo Morgado Avatar answered Sep 20 '22 08:09

Paulo Morgado