Is my understanding of async/await, how it works and its benefits, correct?

前端 未结 1 1066
野的像风
野的像风 2021-02-07 04:43

I\'ve asserted my understanding of async/await on a couple of occasions, often with some debate as to whether or not I\'m correct. I\'d really appreciate it if anyone could eit

相关标签:
1条回答
  • 2021-02-07 05:21

    That's pretty much correct.

    A few notes though:

    • The thread that starts executing an async method is the caller's thread which may, or may not, be a ThreadPool thread.
    • If an await is reached, but the awaitable (usually Task) is already completed the thread will continue executing the rest of the method synchronously.
    • The thread that resumes running the method is usually a ThreadPool thread, but that depends on the SyncrhonizationContext and TaskScheduler.
    • The JIT isn't involved here (not more than usual). The compiler is the one that turns an async method into the state machine. You can see that with this TryRoslyn example.
    • It's true that async-await doesn't necessarily imply concurrency as it could be single threaded. However, it can still be concurrent even with just a single thread by starting and awaiting multiple asynchronous operations at the same time.
    • async-await and the TPL are not completely separate parts. async-await is built on top of the TPL. That's why it's called the Task-based Asynchronous Pattern.
    • While most truly asynchronous operations are I/O, not all are. You also usually delay asynchronously with Task.Delay or use asynchronous synchronization constructs like SemaphoreSlim.WaitAsync.
    0 讨论(0)
提交回复
热议问题