I have following method:
public async Task M1()
{
for (int i = 0; i < 10; i++)
{
await M2();
}
}
public async Task M2()
{
for(int i = 0; i < 10; i++)
{
//synchronous operations
}
}
Will actually marking M2 as async despite it has only sync operations inside will make any difference regarding a way it’s being executed?
>Solution :
No, moreover everything before first await on "truly async" function will be executed syncroniously. Check out the next code:
var task = M1();
Console.WriteLine("before outer await");
await task;
Console.WriteLine("after outer await");
async Task M1()
{
for (int i = 0; i < 2; i++)
{
Console.WriteLine("before await M2");
await M2();
Console.WriteLine("after await M2");
}
Console.WriteLine("before await");
await Task.Delay(100);
Console.WriteLine("after await");
}
async Task M2()
{
for(int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
}
Which will produce output like:
before await M2
// ... numbers
after await M2
before await M2
// ... numbers
after await M2
before await
before outer await
after await
after outer await
And then compare output with the following M2 version:
async Task M2()
{
await Task.Delay(100);
for(int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
}
Which will result in before outer await written earlier (somewhere after first "before await M2").
Some potentially useful links:
- Asynchronous Programming in .NET – Introduction, Misconceptions, and Problems
- Asynchronous programming doc
- Task asynchronous programming model
- How Async/Await Really Works in C# – if you want to dive deeper
- Dissecting the async methods in C# – if you want to dive deeper