anthonypliu
anthonypliu

Reputation: 12437

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?

Upvotes: 4

Views: 221

Answers (4)

dugas
dugas

Reputation: 12473

but when I read from the collection do I have to lock it?

Yes, if it is possible that another thread may modify the dictionary during the read.

What is the correct way to do something like search for a key and return the User in the Dictionary?

Use the TryGetValue method.

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

Upvotes: 3

Tigran
Tigran

Reputation: 62265

If you're using C# 4.0 or more, you can make use of ConcurentDictionary which handles all that stuff.

If you don't have or can not use 4.0 for some reason, yes, you need to implement by yourself locking mechanism on Read, Write and Contains, to simulated basic ACID principles, like

  • Consistensy
  • Isoltaion
  • Durability.

Don't think Atomicity has much deal in this case.

Hope this helps.

Upvotes: 2

Aghilas Yakoub
Aghilas Yakoub

Reputation: 29000

You can use ConcurrentDictionary

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

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564771

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.

Upvotes: 4

Related Questions