ConcurrentDictionary and atomic operations - Lock sometimes required?

Let's say I have this simple code: (simplification)

Where MyConCurrentDictionaryis static ConcurrentDictionary<string, string>(which is in another class).

/*1*/   public void Send(string Message, string UserName)
/*2*/   {            
/*3*/       string ConnectionId;
/*4*/       if (MyConCurrentDictionary.TryGetValue(UserName,out ConnectionId))
/*5*/       {
/*6*/       //...   
/*7*/           DB.InsertMessage( Message, ConnectionId);
/*8*/           LOG.LogMessage  ( Message, ConnectionId);
/*9*/       //...
/*10*/       }
/*11*/       else ...
/*12*/   }

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. (, , ).

+4
2

, : ConcurrentDictionary !

, ReaderWriterLockSlim. , . , .

private ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();

public void DoRead(string xyz)
{
    try
    {
        _lock.EnterReadLock();
        // whatever
    }
    finally
    {
        _lock.ExitReadLock();
    }
}

public void DoWrite(string xyz)
{
    try
    {
        _lock.EnterWriteLock();
        // whatever
    }
    finally
    {
        _lock.ExitWriteLock();
    }
}
+2

.

ConcurentDictionary, , , , lock ( ).

- LOG , , cas ( TryGetValue from MyConcurentDictionary) , LOG.

: , , , . LOG, . , ( = 1 - ).

+1

Source: https://habr.com/ru/post/1541073/


All Articles