Asynchronous Callbacks and Sockets

Hi, I want to learn more about how Asynchronous callbacks work with Sockets .

Say, from my UI thread, I call BeginRead and pass a callback called Read . In my opinion, BeginRead creates a new thread (Thread A) , so code execution in the user interface thread can continue. Callback Read in Thread A to the right? It is blocked in EndRead .

Does Thread A then end auto-closure after the callback completes?

Assuming Thread A closes as soon as the callback is called:

Does this mean that it is safe to call BeginRead inside Thread A before it ends? This BeginRead will create Thread B. Could Thread B fail to execute or correctly place it, will it end at some point because the calling thread A thread has ended? Or are the threads independent of the caller?

+4
source share
2 answers

You have a few misconceptions. When you call BeginRead , the response you are calling will be called from the internal thread pool of your application. Usually a new thread does not start, although there may be one - this is the internal .NET scheduler.

If you put your program aside in the debugger and go to the Threads view, you should see a bunch of these threads named Worker. As a rule, they all sleep and wait for work. This is much faster than if BeginRead the stream every time you want to read. Instead, he uses these workers, who are in the background, ready to go.

And when the callback is complete, the workflow returns to the pool, ready for more action.

As for the rest of your questions:

  • The callback should not be blocked in EndRead . Your application will not have a block. The I / O data will be either buffered, in which case the callback will be executed almost instantly. Or the data will be available much later. In this case, the callback will be executed only after the data appears. This is an important point because it means that while you are waiting for data, there are no threads waiting for anything. The runtime accepts a wait case and calls back when data appears.
  • Yes, it is safe to call another BeginRead from your callback. There are no dependencies. This is actually a good way to do IO this way.
  • Threads never depend on the caller. They are completely autonomous and will die only upon natural termination or when the process itself dies.
+2
source

BeginRead typically uses an operating system tool called async IO. The Windows kernel does not require any thread to be associated with an I / O operation.

I repeat: you can call BeginRead 1000 times, and no other thread starts or blocks.

The operating system pauses your callback in the thread pool, but only when the wait is complete. EndRead completes immediately without waiting.

You can safely call BeginRead from your callback (usually after calling EndRead ).

0
source

All Articles