Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use lock statements in concurrency

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?

like image 695
anthonypliu Avatar asked Jan 15 '23 16:01

anthonypliu


1 Answers

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.

like image 180
Reed Copsey Avatar answered Jan 22 '23 21:01

Reed Copsey