async 和 await 实现原理

2024-06-12 18:32
文章标签 实现 原理 async await

本文主要是介绍async 和 await 实现原理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

来源:http://blog.csdn.net/cjq1234/article/details/7536644

摘要:用串行运行的状态机模拟实现了异步

 

今天在stackOverflow网站看到一个很好的解释,摘抄并发挥一下,

It works similarly to the yield return keyword in C# 2.0.

An asynchronous method is not actually an ordinary sequential method. It is compiled into a state machine (an object) with some state (local variables are turned into fields of the object). Each block of code between two uses of await is one "step" of the state machine.

This means that when the method starts, it just runs the first step and then the state machine returns and schedules some work to be done - when the work is done, it will run the next step of the state machine. For example this code:

[csharp] view plain copy print ?
  1. async Task Demo() {  
  2.   var v1 = foo();  
  3.   var v2 = await bar();  
  4.   more(v1, v2);  
  5. }  
async Task Demo() {var v1 = foo();var v2 = await bar();more(v1, v2);
}



Would be translated to something like:

[csharp]
  1. class _Demo {  
  2.   int _v1, _v2;  
  3.   int _state = 0;  
  4.   Task<int> _await1;  
  5.   public void Step() {  
  6.     switch(this._state) {  
  7.     case 0:  
  8.       foo();  
  9.       this._v1 = foo();  
  10.       this._await1 = bar();  
  11.       // When the async operation completes, it will call this method  
  12.       this._state = 1;  
  13.       op.SetContinuation(Step);  
  14.     case 1:  
  15.       this._v2 = this._await1.Result; // Get the result of the operation  
  16.       more(this._v1, this._v2);  
  17.   }  
  18. }  
class _Demo {int _v1, _v2;int _state = 0;Task<int> _await1;public void Step() {switch(this._state) {case 0:foo();this._v1 = foo();this._await1 = bar();// When the async operation completes, it will call this methodthis._state = 1;op.SetContinuation(Step);case 1:this._v2 = this._await1.Result; // Get the result of the operationmore(this._v1, this._v2);}
}


The important part is that it just uses the SetContinuation method to specify that when the operation completes, it should call the Step method again (and the method knows that it should run the second bit of the original code using the _state field). You can easily imagine that the SetContinuation would be something like btn.Click += Step, which would run completely on a single thread.

The asynchronous programming model in C# is very close to F# asynchronous workflows (in fact, it is essentially the same thing, aside from some technical details), and writing reactive single-threaded GUI applications using async is quite an interesting area - at least I think so - see for example this article (maybe I should write a C# version now :-)).

The translation is similar to iterators (and yield return) and in fact, it was possible to use iterators to implement asynchronous programming in C# earlier. I wrote an article about that a while ago - and I think it can still give you some insight on how the translation works.

answered by Tomas Petricek

大致是说 async 和await模拟了一个状态机(上面的_state变量维持状态),async把一个顺序执行的工作分割成3块,一个是费时工作的前序,一个是费时的工作,还有一个是费时工作的后续,

[csharp]
  1. async Task Demo() {  
  2.   var v1 = 前序工作();  
  3.   var v2 = await 费时工作();  
  4.   后续工作(v1, v2);  
  5. }  
async Task Demo() {var v1 = 前序工作();var v2 = await 费时工作();后续工作(v1, v2);
}



被翻译成状态机
[csharp]
  1. class 状态机{  
  2.     int _v1, _v2;  
  3.     int 状态变量 =起始态;     
  4.     Task<int> _await1;    
  5.     public void Step() {      
  6.         switch(this.状态变量) {     
  7.             case 起始态:         
  8.                 this._v1 = 前序工作();  
  9.                 this._await1 = 费时工作();        
  10.                 // 当费时工作异步完成时, 异步工作将改变状态变量值  
  11.                 this.状态变量= 顺利完成;        
  12.                 继续调用自身即 Step函数;    //op.SetContinuation(Step);      
  13.             case 顺利完成:        
  14.                 this._v2 = this._await1.Result; //费时工作结果       
  15.                 后续工作(this._v1, this._v2);    
  16.     }  
  17. }  
class 状态机{int _v1, _v2;int 状态变量 =起始态;   Task<int> _await1;  public void Step() {    switch(this.状态变量) {   case 起始态:       this._v1 = 前序工作();this._await1 = 费时工作();      // 当费时工作异步完成时, 异步工作将改变状态变量值this.状态变量= 顺利完成;      继续调用自身即 Step函数;    //op.SetContinuation(Step);    case 顺利完成:      this._v2 = this._await1.Result; //费时工作结果     后续工作(this._v1, this._v2);  }
}



事实上我们亦可以在.net framework 4以下向上面的状态机类一样来调用异步函数,这样同步调用的逻辑还是保持住了,也更好理解,最大的好处是对于循环的处理简单多了。

这篇关于async 和 await 实现原理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1055002

相关文章

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

从原理到实战深入理解Java 断言assert

《从原理到实战深入理解Java断言assert》本文深入解析Java断言机制,涵盖语法、工作原理、启用方式及与异常的区别,推荐用于开发阶段的条件检查与状态验证,并强调生产环境应使用参数验证工具类替代... 目录深入理解 Java 断言(assert):从原理到实战引言:为什么需要断言?一、断言基础1.1 语

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Java easyExcel实现导入多sheet的Excel

《JavaeasyExcel实现导入多sheet的Excel》这篇文章主要为大家详细介绍了如何使用JavaeasyExcel实现导入多sheet的Excel,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录1.官网2.Excel样式3.代码1.官网easyExcel官网2.Excel样式3.代码

python实现对数据公钥加密与私钥解密

《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录公钥私钥的生成使用公钥加密使用私钥解密公钥私钥的生成这一部分,使用python生成公钥与私钥,然后保存在两个文

MySQL中的表连接原理分析

《MySQL中的表连接原理分析》:本文主要介绍MySQL中的表连接原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、环境3、表连接原理【1】驱动表和被驱动表【2】内连接【3】外连接【4编程】嵌套循环连接【5】join buffer4、总结1、背景

浏览器插件cursor实现自动注册、续杯的详细过程

《浏览器插件cursor实现自动注册、续杯的详细过程》Cursor简易注册助手脚本通过自动化邮箱填写和验证码获取流程,大大简化了Cursor的注册过程,它不仅提高了注册效率,还通过友好的用户界面和详细... 目录前言功能概述使用方法安装脚本使用流程邮箱输入页面验证码页面实战演示技术实现核心功能实现1. 随机