views:

285

answers:

3

I have multiple threads who all need to write to the same Dictionary. I have a lock on an object that I maintain in order to make sure only 1 thread is updating the dictionary at once. My question is as follows. If one thread tries to update the dictionary while another has a lock, will the thread just know to wait? Will it just fail? If threads just wait, I can I avoid too many of them from waiting, is there a way to say a maximum of five theads can queue, the rest just go on?

A: 

If one thread is holding a lock and a second thread tries to acquire the same lock, the second thread will wait.

Do the threads only write, or do you have read operations as well? If that is the case, you should probably use ReaderWriterLockSlim (unless you already do). That will allow you to have multiple threads reading in parallel, unless a thread is updating in which case it can get exclusive access to the resource.

Fredrik Mörk
A: 

The lock(obj) statement will block any other thread from accessing the shared resource until that thread is complete.

Garrett
A: 

Locks don't protect objects per se. Locks protect other threads from acquiring the same lock. So if a lock is designed to protect a resource (like a dictionary) then other threads have to cooperate and acquire the same lock before accessing the resource (the dictionary). If a thread is ignoring this and accesses the resource non the less, then it may encounter invalid, transient, state in the dictionary and as a result hit all sort of errors. This applies to both read and write operations. Collection classes in .Net come with a property named SyncRoot which is in general the recommended object for all threads to use if multiple thread access is denied. Also as Fredrik already pointed out, there are specialized ReaderWriter types that allow multiple, shared, reads and a single, exclusive, write. More complex schemes like the one you cite (avoid an operation if too many threads are waiting for the resource) are quite difficult to code in a completely safe and correct manner, so is better to avoid such complications and stick to the basic primitives.

Remus Rusanu