I am having trouble understanding the way to use the lock()
statement in my code. I have a couple static collections like so:
private static Dictionary<string, User>() Users = new Dictionary<string, User>();
I constantly add, remove, update, and read from this collection. I realize that when I add, remove, or update I should be locking the Users
, but when I read from the collection do I have to lock it? What is the correct way to do something like search for a key and return the User
in the Dictionary? I was thinking creating a new Dictionary
instance and then copy Users to that and then read from it, or can I just read directly from it?
The best option here would likely to be removing the locks, and using ConcurrentDictionary<string, User>
instead of a Dictionary<string, User>
.
Otherwise, you will need to synchronize your reads as well. You can read from multiple threads, but if a writer will be writing to the dictionary while readers are reading, you need synchronization. ReaderWriterLock
(or ReaderWriterLockSlim
) work well in this scenario, as they can allow multiple readers, but only a single writer. A simple lock
will also work, but will block more often than required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With