我正在使用一个线程来解析数据包并添加到列表中,然后我使用其他线程来查找该列表并解析数据包。
我可以收到数据包并将它们添加到列表中,不知何故另一个线程仍在使用列表的过时版本。我试图使用锁来读取/写入它但仍在发生。
private class SocketInformation
{
public bool open { get; set; }
private ConcurrentQueue<byte[]> packetReceiveQueue = new ConcurrentQueue<byte[]>();
public ConcurrentQueue<byte[]> GetPacketReceiveQueue()
{
return packetReceiveQueue;
}
}
private void NewConnection(StreamSocket socket)
{
SocketInformation socketInformation = new SocketInformation();
socketInformation.open = true;
Task.Run(() => ReadPackets(socket, socketInformation));
Task.Run(() => OnlineLoop(socket, socketInformation));
}
private async void ReadPackets(StreamSocket socket, SocketInformation socketInformation)
{
// ...
Debug.WriteLine("Packet received.");
ConcurrentQueue<byte[]> packetReceiveQueue = socketInformation.GetPacketReceiveQueue();
packetReceiveQueue.Enqueue(packet);
}
private async void OnlineLoop(StreamSocket socket, SocketInformation socketInformation)
{
while (socketInformation.open)
{
ConcurrentQueue<byte[]> packetReceiveQueue = socketInformation.GetPacketReceiveQueue();
for (int i = 0; i < packetReceiveQueue.Count; i++)
{
Debug.WriteLine("Parsing packet.");
byte[] packet = packetReceiveQueue.ElementAt(i);
ParsePacketSequence(socket, socketInformation, packet);
}
}
}
控制台: