简体   繁体   English

ConcurrentDictionary 添加数据

[英]ConcurrentDictionary Add Data

Now, in my project, I have to write the data from different ipaddresses into separate lists.现在,在我的项目中,我必须将来自不同 IP 地址的数据写入单独的列表中。 I am having a problem in how I will record in what order.我在如何按什么顺序记录方面遇到问题。

The number of connections can be 500. The user can close and open connections as they wish.连接数可以是 500。用户可以根据需要关闭和打开连接。 In case he closes the connection, no registration should be made for that list.如果他关闭连接,则不应对该列表进行注册。

For example;例如; The ip address 192.168.1.20 - 192.168.1.30 - 192.168.1.40 is three connections. ip地址192.168.1.20 - 192.168.1.30 - 192.168.1.40是三个连接。 I know from which ip address the data comes from but I cannot control which list I should write the data to.我知道数据来自哪个 ip 地址,但我无法控制应该将数据写入哪个列表。

I have 3 lists named Log_1 Log_2 Log_3.我有 3 个名为 Log_1 Log_2 Log_3 的列表。 In case of opening the connection, I can record respectively.在打开连接的情况下,我可以分别记录。 When he closes the 2nd connection and then reconnects, the queue will be shifted and this will make my administration difficult.当他关闭第二个连接然后重新连接时,队列将被转移,这将使我的管理变得困难。 How can I get out of this situation?我怎样才能摆脱这种情况?

To summarize;总结; I need to keep the data from each ip in separate lists.我需要将每个 ip 的数据保存在单独的列表中。 It must be able to support up to 500 connections.它必须能够支持多达 500 个连接。

I used "ConcurrentDictionary" but ConcurrentDictionary does not add when data comes from the same key.我使用了“ConcurrentDictionary”,但当数据来自同一个键时,ConcurrentDictionary 不会添加。 Is there an alternative?有替代方案吗? Or am I making a mistake somewhere.还是我在某个地方犯了错误。

My Code我的代码

ConcurrentDictionary<string, Queue<byte[]>> FullData = new ConcurrentDictionary<string, Queue<byte[]>>();

DataReceived Code数据接收代码

byte[] Data = e.Data;
        FullData.TryAdd(e.IpPort, Data);

You can access the Queue like this FullData[e.IpPort] and add the new value to your queue.您可以像这样访问Queue FullData[e.IpPort]并将新值添加到您的队列中。

if (!FullData.ContainsKey(e.IpPort))
    FullData.TryAdd(e.IpPort, new ConcurrentQueue<byte[]>());

byte[] Data = e.Data;
        FullData[e.IpPort].Enqueue(Data);

You shoould also probably use ConcurrentQueue in a non thread safe context.您还应该在非线程安全上下文中使用ConcurrentQueue

You want to add the Data to the Queue Keyed by e.IpPort .您想将Data添加到由e.IpPort键入的Queue中。 Use the FullData.GetOrAdd method to retrieve the queue.使用FullData.GetOrAdd方法检索队列。 This will add a new queue (via supplied expression) to the dictionary if they key is not found:如果找不到它们的键,这将向字典添加一个新队列(通过提供的表达式):

var queue = FullData.GetOrAdd(e.IpPort, (key) => new Queue<byte[]>(...));

queue.Enqueue(Data);

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

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