Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when awaiting on already-completed task?

When I construct an instance of a class that I have, I would like to trigger a Token renewal function (async method) and let it run in the background (I keep a reference to the returned Task).

Later on, when a user triggers a request, I would like to await on that Task.

Lets assume that the Task completes after 1 second, and that the user triggers a request after 2 seconds (which means, the Task is completed).

The method that handles the user's request awaits that Task, would it get the value immediately? after all, the Task is completed and holds the value.

like image 366
johni Avatar asked Jul 11 '16 11:07

johni


People also ask

Can you await a task twice?

await hides all this complexity from you, and it allows you to await the same task in ten different places (very useful for e.g. asynchronous lazy initialization). can I be assured that the method pointed by task wont be executed twice even if the task is running or ran already ? @BilalFazlani Yes, you can.

Does Task run need to be awaited?

If it is some trivial operation that executes quickly, then you can just call it synchronously, without the need for await . But if it is a long-running operation, you may need to find a way to make it asynchronous.

How does task Wait work?

Wait is a synchronization method that causes the calling thread to wait until the current task has completed. 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.


1 Answers

The method that handles the user's request awaits that Task, would it get the value immediately?

Yes. You can think of it as being lazy, if you await a task that is already completed it returns immediately. You could await it several times on different threads and it would only return once it has the result (or is faulted).

Task.CompletedTask was added as a nicety for this very reason. You could await this and it would immediately return a successful task as it has already been completed.

like image 110
David Pine Avatar answered Oct 31 '22 13:10

David Pine