c# - Do I need a lock in AddOrUpdate of a concurrent dictionary? -
in class have
public static concurrentdictionary<string, hashset<string>> connecteduserconnections = new concurrentdictionary<string, hashset<string>>(); when adding or updating, should update via:
connecteduserconnections.addorupdate(userid, new hashset<string>(), (key, existingval) => { existingval.add(connectionid); return existingval; }); or
connecteduserconnections.addorupdate(userid, new hashset<string>(), (key, existingval) => { lock(connecteduserconnections) { existingval.add(connectionid); return existingval; } }); many all.
by looking @ public tvalue addorupdate(tkey key, func<tkey, tvalue> addvaluefactory, func<tkey, tvalue, tvalue> updatevaluefactory) reference source,
while (true) { tvalue oldvalue; if (trygetvalue(key, out oldvalue)) //key exists, try update { newvalue = updatevaluefactory(key, oldvalue); if (tryupdate(key, newvalue, oldvalue)) there no lock until trygetvalue, if there value key, multiple threads arrive @ trygetvalue, execute it, return true, execute updatevaluefactory (your method) @ same time , try adding existingval.add(connectionid);...
so yes, need lock.
Comments
Post a Comment