I believe it is because you are re-cycling the buffer when bytesRead == bufferSize
. Imagine these two sequences (I use the term "pointer" loosely here to refer to a reference variable, I think it gets the point across better).
First, when you are below buffer size:
- you make
buffer
point at a new byte array in memory 4096 in size. fs.Read
writes 20 bytes to the objectbuffer
points at.- you make
dataToWrite
point at the same object as buffer. - you make
dataToWrite
point at a new byte array 20 bytes in size. - you copy 20 bytes from the object
buffer
points at to the objectdataToWrite
points at. - you put a pointer to the object
dataToWrite
points at in the blocking collection. fs.Read
writes 30 bytes to the objectbuffer
points at.
Now compare that to what happens if you meet the buffer size.
- you make
buffer
point at a new byte array in memory 4096 in size. fs.Read
writes 4096 bytes to the objectbuffer
points at.- you make
dataToWrite
point at the same object as buffer. - you put a pointer to the object
dataToWrite
points at in the blocking collection. fs.Read
writes 30 bytes to the objectbuffer
points at.
Because dataToWrite
, buffer
, and the item you added to the blocking collection all point at the same object the last fs.Read
will modify the byte array that was just stored in the collection.
Drop your if statement and always allocate a new dataToWrite
and your program should work fine.