我想要做的是让网络上的小组聊天成员保持记忆。我定义了这样一个静态嵌套字典:
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,因此删除它不是原子的。
谢谢。
发布于 2019-02-11 19:04:05
若要从组中删除ChatMember
,您需要为该组获取ConcurrentDictionary<>
。
var groupDictionary = onlineGroupsMembers["groupID"];
...or...
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的...or .
ConcurrentDictionary<string, ConcurrentBag<string>> groupIdToMemberIds;
注意,ConcurrentBag<>
允许重复的值。
在后一种情况下,如果您想要一种快速获取给定成员ID的ChatMember
的方法,您可以使用另一个字典.
ConcurrentDictionary<string, ChatMember> memberIdToMember;
https://stackoverflow.com/questions/54641998
复制相似问题