How to use Multiple Variables for a lock Scope in C#
c#, critical-section, locking, multithreading
Solution
I'd expect it to, though there'd be a case where it could potentially cause a deadlock condition.
Normally, the code will attempt to lock `a` and then proceed to lock `b` if that succeeded. This means that it would only execute the code if it could lock both `a` and `b`. Which is what you want.
However, if some other code has already got a lock on `b` then this code will not do what you expect. You'd also need to ensure that everywhere you needed to lock on both `a` and `b` you attempt to get the locks in the same order. If you get `b` first and then `a` you would cause a deadlock.
Problem
I have a situation where a block of code should be executed only if two locker objects are free. I was hoping there would be something like: ``` lock(a,b) { // this scope is in critical region } ``` However, there seems to be nothing like that. So does it mean the only way for doing this is: ``` lock(a) { lock(b) { // this scope is in critical region } } ``` Will this even work as expected? Although the code compiles, but I am not sure whether it would achieve what I am expecting it to.