如何理解async和await设计模式和如何应用到.net 4以下的framewor

来源:未知 责任编辑:责任编辑 发表时间:2015-10-08 14:15 点击:

因为开发了一些silverlight的东西,对于异步编程是深恶痛绝,把逻辑撕裂,非常难受。

今天在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:

async Task Demo() {
  var v1 = foo();
  var v2 = await bar();
  more(v1, v2);
}

Would be translated to something like:

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 method
      this._state = 1;
      op.SetContinuation(Step);
    case 1:
      this._v2 = this._await1.Result; // Get the result of the operation
      more(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块,一个是费时工作的前序,一个是费时的工作,还有一个是费时工作的后续,

async Task Demo() {
  var v1 = 前序工作();
  var v2 = await 费时工作();

发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
用户名: 验证码:点击我更换图片
最新评论 更多>>

推荐热点

  • 浅析.NET下XML数据访问新机制
  • asp.net 面试+笔试题目第1/2页
  • C# 邮件地址是否合法的验证
  • asp.net 设置GridView的选中行的实现代码
  • C#高级编程:数据库连接[1]
  • ASP.NET&#160;GridView列表代码示例
  • 经典C++程序1
  • 微软ASP.NET站点部署指南(2):部署SQL Server Compact数据库
  • 微软ASP.NET站点部署指南(3):使用Web.Config文件的Transforma
网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
Copyright © 2008-2015 计算机技术学习交流网. 版权所有

豫ICP备11007008号-1