I’m trying to write a fairly simple application that passes data between two sockets. However, I’m a little confused on using the NetworkStream Async operations (BeginRead and EndRead).
For example:
while (myNetworkStream.DataAvailable)
myNetworkStream.BeginRead(mBrowserDataBuffer, 0, mBrowserDataBuffer.Length, new AsyncCallback(ProcessNetworkStreamRead), myNetworkStream);
When I call BeginRead, the method will immediately return and start a thread to perform the read operation. However, in my loop above, what happens if BeginRead gets called AGAIN before the delegate finishes?
Basically I want my delegate to append incoming data to a larger buffer and then processes messages as they are complete. I need to use async operations because while one socket is reading I’d like to also read and process from the other socket as well.
Only one thread must read from the same stream.
One trick is to call
BeginReadagain in yourEndReadcallback. Doing it in the loop as you have shown is not correct.