简体   繁体   中英

Await and async behavior

Given this example:

void Main() { Test().Wait(); }

async Task Test()
{
    Console.WriteLine("Test A");
    await AsyncFunction();
    // It doesn't matter where the await is in AsyncFunction, it will always wait for the function to complete before executing the next line.
    Console.WriteLine("Test B");
}

async Task AsyncFunction()
{
    Console.WriteLine("AsyncFunction A");
    await Task.Yield();
    Console.WriteLine("AsyncFunction B");
}

In no case "Test B" will be displayed before "AsyncFunction B"

The await statement in Test() is not waiting just for Task.Yield() to finish to resume, but for the whole AsyncFunction to finish?

In no case "Test B" will be displayed before "AsyncFunction B"?

No, that will not happen.

The await statement in Test() is not waiting just for Task.Yield() to finish to resume, but for the whole AsyncFunction to finish?

That's right. Since you're awaiting on AsyncFunction , control resumes once the method finishes execution. If you didn't await on it, then the next line would be executed once control returned from await Task.Yield

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM