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 await
s that Task
, would it get the value immediately? after all, the Task
is completed and holds the value.
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.
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.
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.
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.
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