I am new in async programming and my question might look silly. Can anybody, please, explain how async calls work in the following pseudo code example?
public async Task MyMethod()
{
while(true)
{
await Method1();
//do something in MyMethod
await Task.Delay(10000);
}
}
private async Task Method1()
{
//do something in Method1 before await
await Method2();
//do something in Method1 after await
}
private async Task Method2()
{
//do something in Method2 before await
await LongRunMethod();
}
In my understanding, the program works like this
My questions are
Thank you
Is the above steps sequence correct?
No.
The correct sequence is
Note that the task returned by MyMethod never completes normally; if any of those tasks throw exceptions then it completes exceptionally. For simplicity I've ignored the checks for exceptional continuation in your example, since there is no exception handling.
What methods do get control after Method1() and Method2() finish their work?
The remainder of Method1 eventually gets control after the task returned by Method2 is completed. MyMethod eventually gets control after the task returned by Method1 is completed. The exact details of when the continuations are scheduled depends on the context in which the code is running; if they're on the UI thread of a form, that's very different than if they're in worker threads on a web server.
What is going to happen if LongRunMethod() runs longer than 10000ms?
I think you mean what happens if the task returned by LongRunMethod does not complete for more than ten seconds. Nothing particularly interesting happens then. The delay is not started until after LongRunMethod's task is done. You awaited that task.
I think you fundamentally do not understand what "await" means. You seem to think that "await" means "start up this code asynchronously", but that is not at all what it means. The code is already asynchronous by assumption. Await manages asynchrony; it does not create it.
Rather, await is an operator on tasks, and it means if this task is complete then keep going; if this task is not complete then sign up the remainder of this method as the continuation of that task and try to find some other work to do on this thread by returning to your caller.
No code that is after an await executes before the awaited task is completed; await means asynchronously wait for the completion of the task. It does NOT mean "start this code asynchronously". Await is for declaring what points in an asynchronous workflow must wait for a task to finish before the workflow can continue. That's why it has "wait" in the name.
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