title: How does async-await work under the hood?
body: <p>I recently discussed how async-await works and I want to know if I got it correct. </p>
  
  <p>Does async-await work by switching the thread's ESP stack pointer to point to a different stack frame? That would be similar to <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms682661(v=vs.85).aspx" rel="nofollow noreferrer">WINAPI fibres</a> or the old Win3.1 cooperative multitasking.</p>
  
  <p>For example consider this code:</p>
  
  <pre><code>int Foo() {
      int y = ReadSomethingFromConsole();
      int x = await DoSomethingAsync();
      return x+y; 
  }
  </code></pre>
  
  <p>The call stack would look like this:</p>
  
  <pre><code>EventLoop(...);
  .......
  Foo();
  </code></pre>
  
  <p>At the point we reach the <code>await</code> statement, a new task is scheduled to run in the thread pool, and <code>await</code> immediately switches the ESP pointer to point to a new stack frame in which we are at the <code>EventLoop()</code> function. The current stack frame's memory segment is not discarded though, just ESP is no longer pointing to it.</p>
  
  <p>The event loop then runs more events, until it gets notified that the task is complete. At this point ESP is switched to point to the stack segment of the <code>Foo()</code> function.</p>
  
  <p>Do I understand it correctly, is this how it works?  </p>
  
  <p><strong>Edit:</strong> Also how is the new stack frame created by <code>await</code>? Is it copied off of some "template" stack frame snapshot, similar to a VM snapshot?</p>