问题
I'm receiving some data over a socket and trying to add it to a Queue so it can be dequeued by another thread that is much more slow, something like a buffer.
The problem is that everytime I enqueue a new value, all the values in the queue become that.
byte[] aux = new byte[1464];
aux = (byte[])ar.AsyncState;
//add the package to the package fifo list
lock (lockPktBuffer)
{
packetBuffer.Enqueue(aux);
}
First I thought that I was passing a pointer, so all the entries are just pointing to the same variable.
So I tried to do this:
lock (lockPktBuffer)
{
packetBuffer.Enqueue((byte[])ar.AsyncState);
}
But got the same problem.
Any ideia how to work this out ?
回答1:
Here is what's going on (see the comments):
// This line creates a new array
byte[] aux = new byte[1464];
// This line "forgets" the new array, and replaces it with ar.AsyncState:
aux = (byte[])ar.AsyncState;
As the result of this, all additions to the queue happen to enqueue the same object returned from ar.AsyncState
, producing the effect that you see (all instances in the queue look the same).
Here is how you can fix it:
byte[] aux = ((byte[])(ar.AsyncState).ToArray();
...
packetBuffer.Enqueue(aux);
This call makes a copy of ar.AsyncState
into a new array of bytes, making sure that all instances that you enqueue are independent
回答2:
You are passing a reference. When you assign an array to another, it's the reference that is copied, it doesn't copy the data in the array.
To make a copy of the array you need to specifically copy the data inside it. Example:
// get the reference to the source array
byte[] source = (byte[])ar.AsyncState;
// create a new array with the same size
byte[] aux = new byte[source.Length];
// copy all the values from the source
Array.Copy(source, aux, source.Length);
来源:https://stackoverflow.com/questions/23873213/after-every-enqueue-all-the-values-in-the-queue-become-the-same