2

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?

1 Answers1

7

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

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • 2
    @Nathan There aren't many. But more on that [here](http://stackoverflow.com/questions/22645024/when-would-i-use-task-yield) and [here](http://stackoverflow.com/questions/23431595/task-yield-real-usages/23441833#23441833). All it basically does is post the continuation onto the current synchronization context. – Yuval Itzchakov Sep 19 '15 at 15:48