0

Shouldn't the await Subtask() call return control back to the Main function immediately? When I run this program it actually waits till the long running double for loop(inside Subtask) to finish and only returns back to main after the following Task.Delay() is called. Why is it not returning as soon as await Subtask() is called?

static void Main(string[] args)
{
    Console.WriteLine("Main() threadId: " + Thread.CurrentThread.ManagedThreadId);
    SuperTask();
    Console.Read();
}

static async Task SuperTask()
{
    Console.WriteLine("SuperTask threadId: " + Thread.CurrentThread.ManagedThreadId);
    await SubTask();
}

static async Task SubTask()
{
    Console.WriteLine("ThreadId for SubTask before await is: " + Thread.CurrentThread.ManagedThreadId);
    var x = 0;
    for (var i = 0; i < 25000; i++)
    {
        for (var j = 0; j < 250000; j++)
        {
            x -= i;
        }
    }
    await Task.Delay(10000);
    Console.WriteLine("ThreadId for SubTask is: " + Thread.CurrentThread.ManagedThreadId);
}
MrTux
  • 32,350
  • 30
  • 109
  • 146
Abhi
  • 237
  • 3
  • 8

4 Answers4

1

As I explain in my async intro, the async keyword does not start a new thread or anything crazy like that. Every async method begins executing synchronously.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • In that case, shouldn't the SuperTask() return control to Main as soon as it sees the line "await SubTask()"? Why is it waiting for the await inside Subtask before releasing control to Main ? – Abhi May 14 '15 at 02:05
  • @Abhi: Because `await SubTask();` is the same as `Task subTask = SubTask(); await subTask;`. – Stephen Cleary May 14 '15 at 11:46
1

This is by design, the Subtask() method returns as soon as an await statement is reached and the await Delay operation is kicked off. I explain a bit more here

NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61
0

You are probably experiencing some kind of race issue although Console should be immune to that. Check the marked answer to this question: Strange behaviour of Console.ReadKey() with multithreading

Community
  • 1
  • 1
GreenEyedAndy
  • 1,485
  • 1
  • 14
  • 31
0

This is by design. await starts as a synchronous call until it finds another await in the call chain which actually result into a thread creation. In your scenario this is until call to Task.Delay which actually creates a thread (which is doing nothing and just waiting for 10 sec in this case) but the call can now return to the caller. In other case if you put your looping code in Task.Run for example, then control would return immediately to the caller

Sanjay Singh
  • 714
  • 1
  • 8
  • 15