0

I'm aware that the use of async/await does not actually create a new thread -- but I'm struggling to figure out what could lead to the following behavior ->

// .NET 5
using System;
using System.Threading.Tasks;

var f = FakeIOOperation();
Console.WriteLine("then I am called after the await Task.Delay() relinquishes control to the calling method...");
while(true){Console.Write("");}
Console.WriteLine(await f);

async Task<string> FakeIOOperation()
{
    Console.WriteLine("Firstly, I am called...");
    await Task.Delay(5000); // Simulate something like a 5000ms API call
    Console.WriteLine("I shouldn't be printed");
    return "Data";
}

Why does the "I shouldn't be printed" line get printed out when halting the main thread using the infinite while loop? I was under the impression that anything after the await Task.Delay(5000) is only run once we evaluate the result of the Task. Is a new thread actually being created? And why?

  • 1
    `Task.Delay` wraps a `System.Threading.Timer`. Take a look at [the source](https://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Task.cs,5fb80297e082b8d6,references). And async/await doesn't spawn threads for *I/O bound* tasks. But it may for other types.. such as `Task.Run` and `Task.Delay` – Andy Mar 15 '21 at 04:57
  • You are trying to force a deadlock, but the technique to do so works only in a program where the thread has a synchronization context where the `await` would return to, which a console program does not. Without a context, continuations are handled by the thread pool. See duplicate. See https://stackoverflow.com/questions/40343572/simulate-async-deadlock-in-a-console-application if you want an example of async/await deadlock in a console program. – Peter Duniho Mar 15 '21 at 07:20
  • You may want to include the `Thread.CurrentThread.ManagedThreadId` to your experiments, to have a better idea what thread does what. – Theodor Zoulias Mar 15 '21 at 09:08

0 Answers0