I think the main issue here is your misunderstanding of adding a reference type to the queue which you have declared outside your while
-loop.
If you take a close look at the code you provided, you can see you only declare bytesIn
once. You enqueue the bytesIn
, and then rewrite the value of the array. The array is, however, still the same object as before and can thus not be queued again, hence it changes the array to the new value.
So what's it what we actually want to do? We want to;
- Read the stream
- Put the output in a new array-object
- Enqueue the new object
Which is exactly what @dcastro does, but I'll strip down the code for you;
while ((
i = stream.Read(bytesIn, 0, bytesIn.Length)) != 0 //read the contents of the
//stream and put it in
//bytesIn, if available
)
{
var received = new byte[i]; //Create a new, empty array, which we are
//going to put in the queue.
Array.Copy(bytesIn, 0, received, 0, i); //Copy the contents of bytesIn into our new
//array. This way we can reuse bytesIn while
//maintaining the received data.
fifo.Enqueue(received); //Enqueue the new array and thus saving it.
}
For more information, perhaps you should read about Reference types.