When to use lock instructions in concurrency

I'm having trouble understanding how to use the lock() statement in my code. I have a couple of static collections:

 private static Dictionary<string, User>() Users = new Dictionary<string, User>(); 

I constantly add, delete, update and read from this collection. I understand that when I add, delete or update, I have to block Users , but when I read from the collection, do I need to block it? What is the correct way to do something like search for a key and return User in the dictionary? I was thinking of creating a new instance of Dictionary and then copying users to it and then reading from it or just reading it directly?

+4
source share
4 answers

The best option here is probably to remove locks and use ConcurrentDictionary<string, User> instead of Dictionary<string, User> .

Otherwise, you will also need to synchronize your readings. You can read from multiple threads, but if the writer writes to the dictionary while reading readers, you will need synchronization. ReaderWriterLock (or ReaderWriterLockSlim ) works well in this scenario, as they can allow multiple readers, but only one writer. A simple lock will also work, but it will lock more often than required.

+4
source

but when I read from the collection, do I need to block it?

Yes, if it is possible that another thread may change the dictionary while reading.

What is the correct way to do something like search for a key and return the user to the dictionary?

Use the TryGetValue method.

If you are using .Net 4.0 or higher, you can use the ConcurrentDictionary collection, which is thread safe.

+3
source

If you use C# 4.0 or more, you can use ConcurentDictionary , which handles all of these things.

If you don’t have or cannot use 4.0 for any reason, yes, you need to implement a locking mechanism on Read , Write and Contains in order to simulate a basic ACID , for example

  • Consistensy
  • Isoltaion
  • Strength.

Do not think that Atomity has a lot to do in this case.

Hope this helps.

+2
source

You can use ConcurrentDictionary

LIink: http://msdn.microsoft.com/en-us/library/dd287191.aspx

0
source

All Articles