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

相关文章

MyBatis-Plus逻辑删除实现过程

《MyBatis-Plus逻辑删除实现过程》本文介绍了MyBatis-Plus如何实现逻辑删除功能,包括自动填充字段、配置与实现步骤、常见应用场景,并展示了如何使用remove方法进行逻辑删除,逻辑删... 目录1. 逻辑删除的必要性编程1.1 逻辑删除的定义1.2 逻辑删php除的优点1.3 适用场景2.

C#借助Spire.XLS for .NET实现在Excel中添加文档属性

《C#借助Spire.XLSfor.NET实现在Excel中添加文档属性》在日常的数据处理和项目管理中,Excel文档扮演着举足轻重的角色,本文将深入探讨如何在C#中借助强大的第三方库Spire.... 目录为什么需要程序化添加Excel文档属性使用Spire.XLS for .NET库实现文档属性管理Sp

Python+FFmpeg实现视频自动化处理的完整指南

《Python+FFmpeg实现视频自动化处理的完整指南》本文总结了一套在Python中使用subprocess.run调用FFmpeg进行视频自动化处理的解决方案,涵盖了跨平台硬件加速、中间素材处理... 目录一、 跨平台硬件加速:统一接口设计1. 核心映射逻辑2. python 实现代码二、 中间素材处

Java数组动态扩容的实现示例

《Java数组动态扩容的实现示例》本文主要介绍了Java数组动态扩容的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1 问题2 方法3 结语1 问题实现动态的给数组添加元素效果,实现对数组扩容,原始数组使用静态分配

Spring Boot Interceptor的原理、配置、顺序控制及与Filter的关键区别对比分析

《SpringBootInterceptor的原理、配置、顺序控制及与Filter的关键区别对比分析》本文主要介绍了SpringBoot中的拦截器(Interceptor)及其与过滤器(Filt... 目录前言一、核心功能二、拦截器的实现2.1 定义自定义拦截器2.2 注册拦截器三、多拦截器的执行顺序四、过

Python实现快速扫描目标主机的开放端口和服务

《Python实现快速扫描目标主机的开放端口和服务》这篇文章主要为大家详细介绍了如何使用Python编写一个功能强大的端口扫描器脚本,实现快速扫描目标主机的开放端口和服务,感兴趣的小伙伴可以了解下... 目录功能介绍场景应用1. 网络安全审计2. 系统管理维护3. 网络故障排查4. 合规性检查报错处理1.

Python轻松实现Word到Markdown的转换

《Python轻松实现Word到Markdown的转换》在文档管理、内容发布等场景中,将Word转换为Markdown格式是常见需求,本文将介绍如何使用FreeSpire.DocforPython实现... 目录一、工具简介二、核心转换实现1. 基础单文件转换2. 批量转换Word文件三、工具特性分析优点局

Springboot3统一返回类设计全过程(从问题到实现)

《Springboot3统一返回类设计全过程(从问题到实现)》文章介绍了如何在SpringBoot3中设计一个统一返回类,以实现前后端接口返回格式的一致性,该类包含状态码、描述信息、业务数据和时间戳,... 目录Spring Boot 3 统一返回类设计:从问题到实现一、核心需求:统一返回类要解决什么问题?

Java使用Spire.Doc for Java实现Word自动化插入图片

《Java使用Spire.DocforJava实现Word自动化插入图片》在日常工作中,Word文档是不可或缺的工具,而图片作为信息传达的重要载体,其在文档中的插入与布局显得尤为关键,下面我们就来... 目录1. Spire.Doc for Java库介绍与安装2. 使用特定的环绕方式插入图片3. 在指定位

Java使用Spire.Barcode for Java实现条形码生成与识别

《Java使用Spire.BarcodeforJava实现条形码生成与识别》在现代商业和技术领域,条形码无处不在,本教程将引导您深入了解如何在您的Java项目中利用Spire.Barcodefor... 目录1. Spire.Barcode for Java 简介与环境配置2. 使用 Spire.Barco