'How c# async method keeps reference of its parent method

I'm learning c# async/await methods. I don't understand how the async method keeps the reference to its caller method and how it jumps back to it correctly once its execution is done. Will the state machine or thread keeps the reference to it caller?



Solution 1:[1]

This is my simplified understanding of the inner workings, details are probably incorrect, but I hope the overall principle is close enough.

Lets assume you have a task from some source, and you await said task in an async method. This will register a callback delegate in the task that resumes execution of the async method, and it also captures an 'execution context'. When the task completes, regardless of success/exception/cancellation, all the registered callbacks will be called. Depending on context this might involve:

  1. Posting a message to the main thread, asking it to invoke the callback with the result
  2. Queuing the callback on the thread pool
  3. Calling the callback directly

If the task is already completed then the callback may just be executed immediately.

So there will be an indirect reference from the called async method to the calling method, at least if the calling method also awaits the task. But in practice that is not something you should need to care about.

I highly recommend reading the Dissecting the async methods in C# article linked to in the comments by Mat J for a more detailed understanding. I also found Gor Nishanov article on Fibers under the magnifying glass interesting, but it covers how earlier attempts at asynchronicity worked, and how they arguably failed. There is also some articles on Continuation Passing Style (CPS) that might also be interesting, as async/await in some ways can be viewed as CPS with a easier syntax.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1