Uno Uno - 2 months ago 15
C# Question

Await and async behavior

I am trying to get my head around the asynchronous keywords of .NET 4.5.

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?

Answer

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