本文介绍了在每个 Enqueue() 之后,队列中的所有值都变得相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过套接字接收一些数据并尝试将其添加到队列中,以便它可以被另一个慢得多的线程(例如缓冲区)出列.

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.

所以我尝试这样做:

                    lock (lockPktBuffer)
                    {
                        packetBuffer.Enqueue((byte[])ar.AsyncState);
                    }

但遇到了同样的问题.

任何想法如何解决这个问题?

Any ideia how to work this out ?

推荐答案

这是正在发生的事情(见评论):

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;

因此,队列中的所有添加都恰好将 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).

解决方法如下:

byte[] aux = ((byte[])(ar.AsyncState).ToArray();
...
packetBuffer.Enqueue(aux);

此调用将 ar.AsyncState 的副本复制到一个新的字节数组中,确保您入队的所有实例都是独立的

This call makes a copy of ar.AsyncState into a new array of bytes, making sure that all instances that you enqueue are independent

这篇关于在每个 Enqueue() 之后,队列中的所有值都变得相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 16:49