Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 215
zotty Avatar asked Dec 19 '25 04:12

zotty


1 Answers

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);
}
like image 105
dcastro Avatar answered Dec 20 '25 22:12

dcastro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!