JimmyJimm JimmyJimm - 1 month ago 24
Vb.net Question

Async/await execution order

This is the program output:

Program Begin
1 - Starting
2 - Task started
A - Started something
Program End
B - Completed something
3 - Task completed with result: 123


Question: As far i understand when it comes to await process is going back to main context so in this case to Main and then go back to await when it's finished so "A - Started something" should be after "Program End". Why this one line was shown? From my understanding when it comes to away it should immediatly go back to main context.

static void Main(string[] args)
{
Console.WriteLine("Program Begin");
DoAsAsync();
Console.WriteLine("Program End");
Console.ReadLine();
}

static async void DoAsAsync()
{
Console.WriteLine("1 - Starting");
var t = Task.Factory.StartNew<int>(DoSomethingThatTakesTime);
Console.WriteLine("2 - Task started");
var result = await t;
Console.WriteLine("3 - Task completed with result: " + result);
}

static int DoSomethingThatTakesTime()
{
Console.WriteLine("A - Started something");
Thread.Sleep(1000);
Console.WriteLine("B - Completed something");
return 123;
}

Answer

When it comes to await, first the task get triggered, here it is "DoSomethingThatTakesTime". And then goes back to calling method to perform the next task/execution (here in your case it is Main()).

This will be much meaning full if you have another await in the main.

look into below example. very well explained. https://msdn.microsoft.com/en-us/library/mt674892.aspx

You may see a different result, if you call thread sleep before first print statement.