3
votes

I tested console application like this:

class Program
{
    static void Main(string[] args)
    {
        Test();

        Console.WriteLine("C");

        Console.ReadLine();
    }

    static async void Test()
    {
        Console.WriteLine("A");
        await Task.Delay(2000);
        Console.WriteLine("B");
    }
}

This application printed A and C immmediately then B after 2 seconds. It looks fine. But I read an article about async/await "There Is No Thread" (http://blog.stephencleary.com/2013/11/there-is-no-thread.html), it says async/await does not create additional thread.

So back to my console application, I think that the main thread is blokced on Console.ReadLine(), so the remain code in Test() (Console.WriteLine("B")) is not executed until Console.ReadLine() is complete. But actual result is different, the remain code is executed regardless of the blocking of main thread.

I want to know that await works like CPU interrupt, so the instruction pointer is moved to the remain code(Console.WriteLine("B");) and moved back to interrupted position(Console.ReadLine();) after execution?

1
async/await is an abstraction for asynchronous work. In some cases the implementation is based on CPU interupt, in some cases it is based on EPOLL, in some cases it can be based on thread synchronization primitives. - Aron
@KichangKim: There Is No Thread explains how async doesn't have to use a thread, and for I/O operations it generally does not block a thread. However, when an async method continues, it has to run somewhere; I describe this behavior in my async intro post. - Stephen Cleary

1 Answers

6
votes

Unlike a Windows form app, console applications don't have a single "blessed" thread (the UI thread). As such, no special synchronization context is employed by default in console applications and so the continuations that await makes use of are in fact scheduled using the thread pool.

So there's no need to "interrupt" the thread that's currently waiting on Console.ReadLine - another thread is used instead.