Hi I want to know more about how Async Callbacks works with Sockets.
Lets say from my UI Thread i call BeginRead method and pass in a callback named Read . From my understanding, BeginRead spawns a new thread (Thread A) hence code execution in the UI Thread can still proceed. The callback Read is executed in Thread A right? It blocks at the EndRead.
Then does Thread A auto close itself once the callback ends?
In the assumption that Thread A closes itself once the callback is called:::
Does it mean its safe to call another BeginRead inside Thread A just before it ends? This BeginRead will spawn a Thread B. Will Thread B fail to execute or to correctly put it, will it terminate at some point because the calling thread which is Thread A was ended? Or are threads not dependant on the caller at all?
You have a few misconceptions here. When you call
BeginReadthe callback that you specify will be called from within the internal thread pool of your application. There is typically no new thread started, though there might be one – it’s up the the internal scheduler of .NET.If you break your program in the debugger and go to the Threads view you should see a bunch of these threads named Worker threads. Typically all of them are sleeping and waiting for work. This is a much faster way than if
BeginReadwould spin up a thread each time you wanted to read. Instead it uses these workers that lay in the background, ready to go.And when the callback is completed the worker thread goes back to the pool, ready for more action.
As for the rest of your questions:
EndRead. There will be no block in your application. The IO data will be available either buffered, in which case the callback will run almost instantly. Or the data will be available much later. In that case the callback will be executed only after the data has appeared. This is an important point because it means that while you’re waiting for data there are no threads that wait for anything. The runtime takes case of the waiting and produces callbacks when data appears.BeginReadfrom your callback. There are no dependencies. In fact, it is a good way to do IO that way.