4

I am new to asynchronous programming in .Net using C#. All I have understood so far is :

With asynchronous programming, threads that are waiting for a web service or database to return data are freed up to service new requests until the data the is received.

Once the data is received, the thread is restarted and continue processing the code that comes after that call.

Now , I wanted to know in details How the state is managed for the thread so that it can start executing from the point the async call was made.

If it uses a stack to handle that, Can some one please give me an insight into the process?

Thanks,

Mayank

Mayank Joshi
  • 75
  • 1
  • 5
  • 2
    Myabe you can have a look here : https://msdn.microsoft.com/en-us/library/mt674882.aspx – Yanga Nov 10 '16 at 13:38
  • 3
    At the heart of everything is the humble delegate: something that combines both a method and the object it's invoked on. From there we get [closures](http://stackoverflow.com/questions/428617/), and from closures we get state machines as used by async/await. When not using the object of a delegate, state must be passed explicitly ([`IAsyncResult.AsyncState`](https://msdn.microsoft.com/library/system.iasyncresult.asyncstate)), but that's a less common scenario. An entire book can be written on this subject, and I'm pretty sure they actually have been written. – Jeroen Mostert Nov 10 '16 at 13:46
  • 1
    Your async/await code actually gets converted into a struct implementing `IAsyncStateMachine`, which contains all the necessary context fields, and a single `MoveNext` method which will get invoked as each partial task is finished. So, if you understand how calling `BeginInvoke` on any other instance method works, you should understand how the state is being passed along. Tl;dr; local variables are not placed on the stack, but placed in a struct (which is actually soon boxed and placed on the heap). – vgru Nov 10 '16 at 13:49
  • Any answer to this question is either going to be massive, or contains a lot of _'that depends'_. – Gusdor Nov 10 '16 at 13:53
  • 1
    The async state machine is detailed [here](https://codeblog.jonskeet.uk/category/eduasync/). – Stephen Cleary Nov 15 '16 at 02:18
  • thanks for the help.. Your comments does added a lot to my understanding – Mayank Joshi Nov 15 '16 at 09:00

1 Answers1

0

Now , I wanted to know in details How the state is managed for the thread so that it can start executing from the point the async call was made.

Async method are divided into smaller chunks. Basically, when compiling async method, for every await keyword new method is generated.

Keep in mind, that this is a big simplification and it's all done behind the scenes and you really don't need to know how it works in order to use it.

Mateusz Krzaczek
  • 614
  • 5
  • 17