Principles of Async and await implementation

Source: Internet
Author: User

Source: http://blog.csdn.net/cjq1234/article/details/7536644

Absrtact: Using the serial running state machine simulation to realize the asynchronous

Today in the StackOverflow website see a good explanation, excerpt and play it,

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

An asynchronous method isn't actually a ordinary sequential method. It is compiled to a state machine (a) and some state (local variables are turned into fields of the object). Each blocks of code between two uses of await is one ' step ' of the state machine.

This means the starts, it just runs the "the" "the" Les some work to be done-when the work are done, it would run the next step of the state machine. For example this code:

[CSharp] view plain copy print? Async task demo ()  {      var v1 = foo ();     var v2 = await  bar ();     more (v1, v2);  }  

Async Task Demo () {
  var v1 = foo ();
  var v2 = await bar ();
  More (v1, v2);
}



Would be translated to something like:

[CSharp] 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,&NBSP;THIS._V2);     }  }  
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'll 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 this it just uses the Setcontinuation method to specify operation, it completes Call the "step" Method Again (and "method knows" that it should run the second bit of the original code using the _state field). You can easily imagine this 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 t Hing, aside from some technical details), and writing reactive single-threaded GUI applications using Async is quite a in teresting Area-at Least I So-see for example this article (maybe I should write a C # version now:-)).

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

answered by Tomas Petricek

Roughly speaking, async and await simulate a state machine (the above _state variable to maintain state), async the work of a sequential execution into 3 pieces, one is time-consuming work of the first order, one is time-consuming work, there is a time-consuming work of the follow-up,

[CSharp]Async Task Demo () {var v1 = pre-order work ();     var v2 = await time consuming work ();   Follow-up work (V1, v2); }
Async Task Demo () {
  var v1 = pre-order work ();
  var v2 = await time consuming work ();
  Follow-up work (V1, v2);
}



Be translated into a state machine
[CSharp] class  state machine {       int _v1, _v2;        int  state variable  = starting state;          Task<int> _await1;          public void step ()  {                switch (this. Status variable)  {                   case  starting State:                            this._v1 =  Pre-order work ();                    this._await1 =  time-consuming work ();                           //&nBSP;,  asynchronous work will change the state variable value               when the time consuming work is done asynchronously       this. State variable =  successfully completed;                          continue to call itself that   step function;     //op. Setcontinuation (step);                    case  successfully completed:                          this._v2 = this._ Await1. result; //time-consuming work results                           follow-up work (THIS._V1,&NBSP;THIS._V2);         }  }  
Class state machine {
    int _v1, _V2;
    int state variable = starting state;   
    Task<int> _await1;  
    public void Step () {    
        switch (this. State variable) {case   
            start state:       
                THIS._V1 = pre-order work ();
                This._await1 = time-consuming work ();      
                When a time-consuming work completes asynchronously, the asynchronous work will change the state variable value this
                . state variable = successfully completed;      
                Continue to call itself the step function;    //op. Setcontinuation (step);    
            Case successfully completed:      
                THIS._V2 = this._await1. result; Time-consuming work Results     
                follow-up (THIS._V1, THIS._V2);  
    }



In fact, we can also invoke asynchronous functions like the state machine class above in the. NET Framework 4, so that the logic of the synchronous invocation is maintained and understood, and the biggest benefit is that the loop is much simpler to handle.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.