I want to store a collection (hashset) as the value in a concurrent dictionary. The code I have works fine as such when testing in isolation.
The question I have though when I retrieve the collection value from the concurrent dictionary should I use a lock when modifying/reading the collection value to avoid another thread updating the collection after I have read the collection from the current dictionary.
The system is a web app with a high degree of concurrency and there will be many threads attempting to update the collection stored in the concurrent dictionary. So want to avoid to any sort of race conditions in terms of reading/modifying the collection value I store in the concurrent dictionary.
ConcurrentDictionary<Guid, HashSet<string>> dictionary = new ConcurrentDictionary<Guid, HashSet<string>>();
userSession.Add(newSessionId);
// userSession.Remove(newSessionId)
vs.
ConcurrentDictionary<Guid, HashSet<string>> dictionary = new ConcurrentDictionary<Guid, HashSet<string>>();
var userSessions = new HashSet<string>();
dictionary.TryGetValue(accountId,out userSessions);
lock(userSession)
{
userSession.Add(newSessionId);
// userSession.Remove(newSessionId)
}