Search code examples
c#concurrent-queue

All items in ConcurrentQueue<byte[]> are identical


I have a NetworkStream that I use to get data from another program. The data arrives as a Byte[64], which I then Enqueue to a ConcurrentQueue so that another thread can dequeue for analysis later. The queue is instantiated:

ConcurrentQueue<byte[]> fifo = new ConcurrentQueue<byte[]>();

then I Enqueue all the data being sent:

Byte[] bytesIn = new Byte[64];
int i;
while ((i = stream.Read(bytesIn, 0, bytesIn.Length)) != 0)
{
    fifo.Enqueue(bytesIn);
}

If I then look at (during debug) the data in fifo it turns out that every byte[64] contained therin is identical to the latest bytesIn. How do I ensure that the arrays I'm adding to fifo are the values and not the pointers (if that's the correct terminology)?


Solution

  • Enqueue a copy of the array instead. You can use the ToArray extension for this.

    while ((i = stream.Read(bytesIn, 0, bytesIn.Length)) != 0)
    {
        var received = bytesIn.Take(i).ToArray();
        fifo.Enqueue(received);
    }
    

    I also used Take to trim the buffer, and copy only the bytes that were received.

    Alternatively, as suggested by @hvd in the comments, using Array.Copy will be faster

    while ((i = stream.Read(bytesIn, 0, bytesIn.Length)) != 0)
    {
        var received = new byte[i];
        Array.Copy(bytesIn, 0, received, 0, i);
    
        fifo.Enqueue(received);
    }