简体   繁体   English

任务间共享列表

[英]List shared between tasks

I'm using one thread to parse the packets and add to the list, then I'm using other thread to itinerate that list and parse the packet. 我正在使用一个线程来解析数据包并添加到列表中,然后我正在使用另一线程来迭代该列表并解析数据包。

I can receive the packets and add them to the list, somehow the other thread is still using the outdated version of the list. 我可以接收到数据包并将它们添加到列表中,而其他线程仍在使用列表的过时版本。 I tried to use lock to read/write to it but is still happening. 我试图使用锁来读取/写入它,但仍在发生。

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

Console: 安慰:

  1. Packet received. 收到数据包。
  2. Packed added to the queue. 打包添加到队列中。
  3. Parsing packet. 解析数据包。
  4. Packet received. 收到数据包。
  5. Packed added to the queue. 打包添加到队列中。
  6. (Second packet not parsed, list outdated) (第二个数据包未解析,列表已过时)

There are Thread-Safe Collections built-in to .net. .net内置了线程安全集合 Find the one that best suits your need. 查找最适合您的需求。 (Looks like ConcurrentQueue would be best - it's FIFO.) (看起来ConcurrentQueue最好-它是FIFO。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM