Call stack may contain several methods returning Task
. If all of them are decorated with async
, the flow of execution is quite simple. However, what if one of them is not await
ed – are other method calls from that method executed asynchronously or not?
Here's an example:
If I have
async Task A()
{
...
await B();
...
}
and if I call A();
and not await (A);
– will await B();
be awaited?
Best Answer
In .net the
async await
keywords are an extension of the Task Parallel Library. When you do notawait
anasync
method it is almost equivalent to callingTask.Run(()=>A())
(There are some gotchas regarding UI threads or other single threaded applications here as with out
.ConfigureAwait(false)
, when creating the task, the awaited code will try to pick up on the same thread context. If you are awaiting from a background worker thread context then await andTask.Run()
are running in the same context. If you are on the UI thread then the context ofTask.Run()
and the awaited context are different.)In your example A() would start, return control at
await B()
and then the code callingA()
would continue whileA()
was waiting forB()
to complete.A simple example would be the following:
When the main method calls
A()
execution is serial until theawait B()
. AfterA()
calls await, control is returned to main which then finishes. At this pointA()
is still out there running "Fire and Forget", which is bad in the case of a console program so we need to make sure that the main thread does not complete beforeA()
finishes. If we don't have theConsole.ReadLine();
the program will end after the call toawait
inA()
.