anon
anon

Reputation:

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?

Upvotes: 2

Views: 114

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149518

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

Upvotes: 7

Related Questions