如何从嵌套的 ConcurrentDictionary 中删除项目?

How to remove an item from a nested ConcurrentDictionary?

我想做的是将在线群聊成员保存在内存中。我定义了一个这样的静态嵌套字典:

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 but it does not help and checking for ContainsKey 然后删除它不是原子的。

谢谢。

要从组中删除 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 映射到其 ChatMemberConcurrentBag<> or a concurrent HashSet<>(如果存在)...

ConcurrentDictionary<string, ConcurrentBag<ChatMember>> groupIdToMembers;

...或从组 ID 到其成员 ID...

ConcurrentDictionary<string, ConcurrentBag<string>> groupIdToMemberIds;

请注意 ConcurrentBag<> 允许重复值。

在后一种情况下,如果您想快速获取给定会员 ID 的 ChatMember,您可以为此使用另一个字典...

ConcurrentDictionary<string, ChatMember> memberIdToMember;