C # - Locking a resource when retrieving from a dictionary

I have a dictionary that tracks objects (ClientObject). The dictionary and ClientObject are accessed by multiple threads. When I modify or read an object in this dictionary, I get a read or write lock in the dictionary using ReaderWriterLockSlim (rwl_clients), and then get an exclusive lock for the actual object.

I just wanted to know if I am using these .net streams correctly.

Example:

rwl_clients.EnterReadLock();
ClientObject clobj;
if(!m_clients.TryGetValue(key, out clobj))
    return;
rwl_clients.ExitReadLock();

SomeMethod(clobj);

SomeMethod (ClientObject clobj) will do something like:

lock(clobj) {

/// Read / Write operations on clobj

}

(ClientObject) , ? , .net ( ) ?

, - Remove()

:

rwl_clients.EnterWriteLock();
ClientObject clobj;
if(m_clients.TryGetValue(key, out clobj)) {
     lock(clobj) {
          m_clients.Remove(key);
     }
}
rwl_clients.ExitWriteLock();

! .

+3
2

(ClientObject) , ? , .net ( ) ?

- , no. , , .

, - Remove()

, , .

- , ? , , , , .

+4

, .

, . , , , .

+1

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


All Articles