title: How do yield and await implement flow of control in .NET?
body: <p>As I understand the <code>yield</code> keyword, if used from inside an iterator block, it returns flow of control to the calling code, and when the iterator is called again, it picks up where it left off.</p>
  
  <p>Also, <code>await</code> not only waits for the callee, but it returns control to the caller, only to pick up where it left off when the caller <code>awaits</code> the method.</p>
  
  <p>In other words-- <a href="http://blog.stephencleary.com/2013/11/there-is-no-thread.html" rel="noreferrer">there is no thread</a>, and the "concurrency" of async and await is an illusion caused by clever flow of control, the details of which are concealed by the syntax.</p>
  
  <p>Now, I'm a former assembly programmer and I'm very familiar with instruction pointers, stacks, etc. and I get how normal flows of control (subroutine, recursion, loops, branches) work.  But these new constructs-- I don't get them.</p>
  
  <p>When an <code>await</code> is reached, how does the runtime know what piece of code should execute next?  How does it know when it can resume where it left off, and how does it remember where?  What happens to the current call stack, does it get saved somehow?  What if the calling method makes other method calls before it <code>await</code>s-- why doesn't the stack get overwritten?  And how on earth would the runtime work its way through all this in the case of an exception and a stack unwind?</p>
  
  <p>When <code>yield</code> is reached, how does the runtime keep track of the point where things should be picked up?  How is iterator state preserved?</p>