Normally I can do something like this to fill up the byte array with stream data:
byte[] dataLength = new byte[4];
clientStream.Read(dataLength, 0, dataLength.Length);
And that fills up the byte array.. However, I’ve been experimenting with async calls and my code looks like this:
byte[] dataLength = new byte[4];
clientStream.BeginRead(dataLength, 0, dataLength.Length, Read, clientStream);
private void Read(IAsyncResult async)
{
NetworkStream clientStream = (NetworkStream)async.AsyncState;
clientStream.EndRead(async);
byte[] dataLength = new byte[4]; // ..?
clientStream.Read(dataLength, 0, dataLength.Length); // Have to re-read in data with synchronous version?..
int result = BitConverter.ToInt32(dataLength, 0);
}
Which I feel is completely.. wrong. What is the point of the async call if you just have to read it all over again in the callback synchronously? How can I access the already read-in bytes without making the dataLength a member variable of the class? Obviously I don’t want to do that because there is more than one connection and they all have different values..
I feel like I’m missing something obvious here..
You do not have to read it all over again – when you call
it returns the number of bytes that have been read, so you will want to do:
At this point your buffer has been filled with those bytes, reading from the stream in a synchronous fashion would just read more bytes.
If you do not want to make your buffer an instance variable you could use a closure with a delegate instead:
Edit:
A better solution might be to put all the state in form of a custom class and pass it in
BeginRead():