There are two separate questions here:
- Use one combination lock or two separate locks
- Whether to use separate objects for blocking or the lists themselves (or their
SyncRoot s)
To some extent, they are separable - if you use two separate locks, you can create two separate objects for locking, one for each list.
If you want MethodThatUsesAList and MethodThatUsesBList to work simultaneously, you will need two separate locks. Then you will need to make sure that at any time when you can purchase both locks, you purchase them in the same order. This means talking about the entire codec in any method that receives a lock: you need to make sure that it does not call another method, which, for example, acquires a different lock.
If your specific scenario is unlikely to suffer from all methods that are effectively blocked for other threads by any thread executing any of them, I would use only one lock for simplicity.
In any case, I would personally go for "private" locks, which no other code knows about. It's easier for me to talk about code written this way. Using the list itself or the synchronization root may very well be absolutely accurate - but I just prefer to think of locks that can't get anything.
source share