async/await. Where is continuation of awaitable part of method performed?

前端 未结 3 867
长情又很酷
长情又很酷 2021-01-01 02:51

I am really curious how async/await enables your program not to be halted. I really like the way how Stephen Cleary explains async/await: \"I like to think of \"await\"

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-01 03:32

    If by "awaitable code" you mean the actual asynchronous operation, then you need to realize that it "executes" outside of the CPU so there's no thread needed and no code to run.

    For example when you download a web page, most of the operation happens when your server sends and receives data from the web server. There's no code to execute while this happens. That's the reason you can "take over" the thread and do other stuff (other CPU operations) before awaiting the Task to get the actual result.

    So to your questions:

    1. It "executes" outside of the CPU (so it's not really executed). That could mean the network driver, a remote server, etc. (mostly I/O).

    2. No. Truly asynchronous operations don't need to be executed by the CLR. They are only started and completed in the future.


    A simple example is Task.Delay which creates a task that completes after an interval:

    var delay = Task.Delay(TimeSpan.FromSeconds(30));
    // do stuff
    await delay;
    

    Task.Delay internally creates and sets a System.Threading.Timer that will execute a callback after the interval and complete the task. System.Threading.Timer doesn't need a thread, it uses the system clock. So you have "awaitable code" that "executes" for 30 seconds but nothing actually happens in that time. The operation started and will complete 30 seconds in the future.

提交回复
热议问题