我试图做的是让群聊的在线成员留在记忆中。我定义了一个静态嵌套字典,如下所示:private static ConcurrentDictionary<string, ConcurrentDictionary<string, ChatMember>> onlineGroupsMembers = new ConcurrentDictionary<string, ConcurrentDictionary<string, ChatMember>>();然后,当新成员到达时,我添加它: onlineGroupsMembers.AddOrUpdate (chatKey, (k) => // add new { var dic = new ConcurrentDictionary<string, ChatMember>(); dic[chatMember.Id] = chatMember; return dic; }, (k, value) => // update { value[chatMember.Id] = chatMember; return value; });现在的问题是,如何从内部字典中删除成员?还如何在外部字典中删除空的字典?并发字典有 TryRemove,但它没有帮助,检查 ContainsKey 然后删除它不是原子的。谢谢。
1 回答
慕哥6287543
TA贡献1831条经验 获得超10个赞
要从组中删除 a,您需要获取该组的...ChatMember
ConcurrentDictionary<>
var groupDictionary = onlineGroupsMembers["groupID"];
...或。。。
var groupDictionary = onlineGroupsMembers.TryGetValue("groupID", out ConcurrentDictionary<string, ChatMember> group);
然后,您将尝试删除该成员...groupDictionary
var wasMemberRemoved = groupDictionary.TryRemove("memberID", out ChatMember removedMember);
要从中完全删除组,请直接在该字典上调用...onlineGroupsMembers
TryRemove
var wasGroupRemoved = onlineGroupsMembers.TryRemove("groupID", out ConcurrentDictionary<string, ChatMember> removedGroup);
实现此目的的一种不那么麻烦的方法可能是使用两个未嵌套的字典。人们会从组ID映射到类似ConcurrentBag<>
或并发HashSet<>
(如果存在)的东西。ChatMember
ConcurrentDictionary<string, ConcurrentBag<ChatMember>> groupIdToMembers;
...或从组 ID 到其成员 ID...
ConcurrentDictionary<string, ConcurrentBag<string>> groupIdToMemberIds;
请注意,允许重复值。ConcurrentBag<>
在后一种情况下,如果您想要一种快速获取给定成员ID的方法,则可以使用另一个字典来获取...ChatMember
ConcurrentDictionary<string, ChatMember> memberIdToMember;
- 1 回答
- 0 关注
- 86 浏览
添加回答
举报
0/150
提交
取消