IMHO, Re-entering a lock is not what you need to take care to avoid (given that for many people, the mental lock model is dangerous at best, see Change below). The point of the documentation is to explain that the thread cannot block itself using Monitor.Enter . This does not always apply to all synchronization mechanisms, frameworks, and languages. Some have non-ad-hoc synchronization, in which case you should be careful that the thread does not block itself. What you need to be careful always calls Monitor.Exit for every call to Monitor.Enter . The lock keyword does this for you automatically.
Trivial re-entry example:
private object locker = new object(); public void Method() { lock(locker) { lock(locker) { Console.WriteLine("Re-entered the lock."); } } }
The thread entered the lock twice on the same object, so it must be released twice. Usually this is not so obvious, and there are various methods that call each other, which are synchronized on the same object. The fact is that you do not need to worry about blocking the stream.
However, you should try to minimize the amount of time it takes to lock. Acquiring a lock is not expensive computing, contrary to what you can hear (it is on the order of a few nanoseconds). Lair rivalry is that expensive.
Edit
Please read Eric’s comments below for more information, but the summary is that when you see lock , your interpretation should be that “all activations of this code block are associated with one thread” and not as it is usually interpreted , "all activations of this code block are performed as a single atomic unit."
For example:
public static void Main() { Method(); } private static int i = 0; private static object locker = new object(); public static void Method() { lock(locker) { int j = ++i; if (i < 2) { Method(); } if (i != j) { throw new Exception("Boom!"); } } }
Obviously, this program is exploding. Without lock this is the same result. The danger is that lock leads you into a false sense of security that nothing can change the state on you between initializing j and evaluating if . The problem is that you (possibly inadvertently) have a Method recursive into itself, and lock will not stop this. As Eric points out in his answer, you may not be aware of this problem until one day someone puts in line too many actions at the same time.
mike z
source share