在任务之间共享的列表

本文关键字:列表 共享 之间 任务 | 更新日期: 2023-09-27 18:35:32

我使用一个线程来解析数据包并添加到列表中,然后我使用另一个线程来巡回该列表并解析数据包。

我可以接收数据包并将它们添加到列表中,不知何故,另一个线程仍在使用列表的过时版本。我尝试使用锁来读/写它,但仍然在发生。

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);
        }
    }
}

安慰:

  1. 收到数据包。
  2. 已打包添加到队列中。
  3. 解析数据包。
  4. 收到数据包。
  5. 已打包添加到队列中。
  6. (第二个数据包未解析,列表已过时)

在任务之间共享的列表

.net 内置了线程安全集合。找到最适合您需求的产品。(看起来ConcurrentQueue是最好的 - 它是FIFO。