Reputation: 65
When the method using await is not itself awaited, execution of the calling method continues before the called method has completed
I got this understanding from here https://www.pluralsight.com/guides/understand-control-flow-async-await
I tried to implement my understanding of async/await via a simple program. I imagined the output as: "Finish" would be printed before the complete execution of CallMethodAsync() as I have called two separate asynchronous methods from there using await, but it's running synchronously as if async-await is not implemented at all.
I want to print finish before the complete execution of CallMethodAsync is done. Let me know where, what am I doing wrong here?
I have seen other posts on StackOverflow for this but I guess, could not understand exactly how async-await works.
class Program
{
public static void Main(string[] args)
{
TestAsync a = new TestAsync();
a.CallMethodAync();
Console.WriteLine("Finish");
}
}
class TestAsync
{
public async Task Method1Async()
{
for(int i = 1; i <= 100; i++)
{
Console.WriteLine("Method 1: " + i);
}
}
public async Task Method2Async()
{
for (int i = 1; i <= 100; i++)
{
Console.WriteLine("Method 2: " + i);
}
}
public async Task<int> CallMethodAync()
{
Console.WriteLine("Before mehtod 1");
await Method1Async();
Console.WriteLine("After method 1. before method 2");
await Method2Async();
Console.WriteLine("after method 2");
return 1;
}
}
Upvotes: 0
Views: 257
Reputation: 1500225
When compiling your code, you should have received warnings that gave you a hint what was wrong:
warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
An async method will run synchronously until it reaches the first await
expression where the value it's awaiting isn't already completed.
In your case, all your async methods return completed tasks - Method1Async
and Method2Async
will simply run synchronously, then return a completed task, which means that CallMethodAsync
will await those already-completed tasks, and itself complete synchronously.
If you add something like await Task.Yield()
in Method1Async
and Method2Async
, then you'll see genuine asynchronous behavior: those methods will return incomplete tasks (when they reach Task.Yield
) which means CallMethodAsync
itself will return an incomplete tasks, etc.
Upvotes: 6