c# - 这是 async-await 工作原理的正确图表吗?

标签 c# .net multithreading asynchronous async-await

我将尝试就 async-await 发表演讲,并且我正在创建一个流程图,试图显示可能的执行顺序。

enter image description here

我试图以段落为基础

The beginning of an async method is executed just like any other method. That is, it runs synchronously until it hits an “await” (or throws an exception).

The “await” keyword is where things can get asynchronous. Await is like a unary operator: it takes a single argument, an awaitable (an “awaitable” is an asynchronous operation). Await examines that awaitable to see if it has already completed; if the awaitable has already completed, then the method just continues running (synchronously, just like a regular method).

If “await” sees that the awaitable has not completed, then it acts asynchronously. It tells the awaitable to run the remainder of the method when it completes, and then returns from the async method.

Later on, when the awaitable completes, it will execute the remainder of the async method. If you’re awaiting a built-in awaitable (such as a task), then the remainder of the async method will execute on a “context” that was captured before the “await” returned.

来自 http://blog.stephencleary.com/2012/02/async-and-await.html

最佳答案

usr 的回答基本上是正确的,尽管我认为它在线程和任务之间进行了过于强烈的类比。任务不必像另一个线程那样。请记住,线程是 worker ,任务是工作。你可以在你的待办事项 list 上列出一百件事,而无需雇用任何 worker 来做。尽量不要将任务视为轻量级 worker ,因为它们不是。它们是需要完成的工作;工作人员做什么取决于交给您任务的代码。

您的图表开始时很好,但在“调用者是否完成了所有独立工作?”时偏离了轨道。调用者的延续是,嗯,不管它是什么。如果这种延续涉及做功,那么它确实有用。其中一些工作可能是安排任务在当前线程上运行。其中一些工作可能是保持 UI 响应。

此外,不要忘记调用者的线程可能会终止,任务的继续可能会安排到另一个线程。

这里可以发生很多很多事情;如果不了解调用者到底在做什么以及调用者的线程上下文是什么,就不可能说出 await 返回后立即发生了什么。

关于c# - 这是 async-await 工作原理的正确图表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41090829/

相关文章:

c# - 在卡住分辨率之前无法返回值(将 Umbraco 版本 4.9.1 升级到 4.11.1)

c# - 设置程序必须在启动时从安装程序运行

.net - X509Certificate2 使 IIS 崩溃

c# - ADFS 身份验证期间的间歇性重定向循环

c# - C# 中的枚举类型约束

C# 获取两个日期时间对象之间的整小时值

c# - 文本框中要标记的倒计时字符不起作用

java - Spring Boot 中的多线程 cron 作业

java - onClick() 设置增量和延迟

java : Is Thread priority changed by JVM(implicitly)