Let's say I have this simple code: (simplification)
Where MyConCurrentDictionaryis static ConcurrentDictionary<string, string>(which is in another class).
public void Send(string Message, string UserName)
{
string ConnectionId;
if (MyConCurrentDictionary.TryGetValue(UserName,out ConnectionId))
{
DB.InsertMessage( Message, ConnectionId);
LOG.LogMessage ( Message, ConnectionId);
}
else ...
}
This method is executed from many instances. (signalR hub if you do)
I need to insert DB/ log ONLY if exists user/connectionID.
So a string #4is thread safe when multiple threads are accessingConcurrentDictionary
But there is another method that is RemoveUser - which removes the user from the dictionary:
public void RemoveUser (string userName)
{
string removed;
if ( MyConCurrentDictionary.TryRemove(userName,out removed ))
Clients.All.removeClientfromChat(userName);
}
But it is possible that contexts will occur on the line #5that will do RemoveUserand REMOVE the username from ConcurrentDictionary.
So, to solve this - the code will be something like this:
lock(locker)
{
if (MyConCurrentDictionary.TryGetValue(UserName,out ConnectionId))
{
}
}
ConcurrentDictionary.
, ConcurrentDictionary?
nb, ConcurrentDictionary . , , , ConcurrentDictionary, lock. (, , ).