Reputation: 1977
I am not sure my understanding of Await is right. The sequence of output is different from what I expected.
Here is the calling code.
internal class Program
{
private static void Main(string[] args)
{
var levelOne = new LevelOne();
levelOne.Work();
Console.WriteLine("Waiting for answer...");
Console.ReadLine();
}
}
This is LevelOne class
public class LevelOne
{
public async void Work()
{
Console.WriteLine("Starting work.");
await LevelTwo.SomeRandomWork();
Console.WriteLine("Work done.");
}
}
And finally this is LevelTwo class
public class LevelTwo
{
public static async Task SomeRandomWork()
{
Thread.Sleep(5000);
Console.WriteLine("Here I am");
var someRandomNumber = await KillTime();
Console.WriteLine("Answer " + someRandomNumber);
someRandomNumber = await KillTime();
Console.WriteLine("Answer again: " + someRandomNumber);
}
private static async Task<long> KillTime()
{
await Task.Delay(TimeSpan.FromMilliseconds(5000));
Random random = new Random();
return random.Next(100000, 900000);
}
}
What I see is
Starting work.
Here I am
Waiting for answer...
Answer 352100
Answer again: 453356
Work done.
Here is the output I expect.
Starting work.
Waiting for answer...
Here I am
Answer 141710
Answer again: 530010
Work done.
Shouldn't the control come back to caller code after the await in LevelOne's Work method is hit? The control does not come back till the await in the LevelTwo's is hit.
Upvotes: 0
Views: 176
Reputation: 726569
This is because you are using Thread.Sleep
instead of await Task.Delay(...)
inside SomeRandomWork()
. That is why the code up to the first await
inside SomeRandomWork()
is executed synchronously before the await
inside Work()
yields control:
public static async Task SomeRandomWork() {
await Task.Delay(1000);
Console.WriteLine("Here I am");
var someRandomNumber = await KillTime();
Console.WriteLine("Answer " + someRandomNumber);
someRandomNumber = await KillTime();
Console.WriteLine("Answer again: " + someRandomNumber);
}
Once you make the switch, the output changes to what you expected:
Starting work.
Waiting for answer...
Here I am
Answer 598694
Answer again: 353771
Work done.
Upvotes: 1