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.
source share