Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does marking a method async when it contains only synchronous calls actually causes async execution?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading