Firstly, _lock should not be static. Or do you want multiple instances of the object to block each other? Secondly, you should have only one synchronized method in the class. Moreover, you should avoid dependencies between synchronized methods in your class. Otherwise, you risk that your method caller will do this incorrectly and get unexpected behavior.
Consider, for example, this code:
class Synchronized { object lockObj = new object(); int counter = 100; public void Decrement() { lock (this.lockObj) { this.counter--; } } public int IsZero() { lock (this.lockObj) { return this.counter == 0; } } }
Now, what will do with the shared synchronized instance?
Use it like this:
while (!synchronized.IsZero()) { synchronized.Decrement(); }
Now thread 1 calls Decrement, the counter gets 0 and immediately thread 2 calls Decrement, because it was expecting a lock in the Decrement method, not IsZero. The counter is now -1, and the loop is infinite.
Not that the locking mechanism was incorrectly programmed, but the caller did not use it well. If you only exposed one synchronized method in your synchronous class, you would not deceive the programmer to blindly believe it.
It should be something like this:
class Synchronized { object lockObj = new object(); int counter = 100; public bool IfNotZeroDecrement() { lock (this.lockObj) { if (this.counter > 0) this.counter--; return this.counter > 0; } } }
source share