I have a Dictionary that tracks objects (ClientObject). Both the dictionary and ClientObject's are accessed by multiple threads. When I modify or read any object in this dictionary, I obtain a read or write lock on the dictionary using ReaderWriterLockSlim (rwl_clients) then obtain an exclusive lock on the actual object.
I just wanted to know if I am using these .net threading facilities correctly
Example:
rwl_clients.EnterReadLock();
ClientObject clobj;
if(!m_clients.TryGetValue(key, out clobj))
return;
rwl_clients.ExitReadLock();
SomeMethod(clobj);
SomeMethod(ClientObject clobj) would do something like:
lock(clobj) {
/// Read / Write operations on clobj
}
Does getting and locking a value (ClientObject) from the dictionary in one thread mean that other threads will respect that lock? In other words, does .net see a value in the dictionary as a single resource (and not a copy) and will therefore respect a lock on that resource in all threads?
One more question, when removing a resource from the dictionary - should I lock it before performing Remove()
Example:
rwl_clients.EnterWriteLock();
ClientObject clobj;
if(m_clients.TryGetValue(key, out clobj)) {
lock(clobj) {
m_clients.Remove(key);
}
}
rwl_clients.ExitWriteLock();
I have learned so much from this site and appreciate any responses! Thanks.