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 aDictionary<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(orReaderWriterLockSlim) work well in this scenario, as they can allow multiple readers, but only a single writer. A simplelockwill also work, but will block more often than required.