Please read the following sample code with Monitor.Enter and Monitor.Exit. Does the lock work?
class LockMe { private static int counter = 0; public void Lock() { Monitor.Enter(counter); counter++; Monitor.Exit(counter); }
No! The code actually is totally wrong. You are not supposed to lock a value type, which doesn’t have a SyncBlock field. Monitor.Enter(counter) will cause an int(counter) to be boxed first and then you are getting the lock from a box object, not the int itself. The lock won’t work as you expected, since a different object(a different SyncBlock) will be used each time.