Why doesn't locking in this code work?

I wrote a simple code (attached), and I do not understand why the lock on some block does not block the area.

The code:

object locker = new object(); private void foo(int i) { Console.WriteLine( string.Format( "i is {0}", i ) ); lock( locker ) { while( true ) { Console.WriteLine( string.Format( "i in while loop is {0}", i ) ) ; foo( ++i ); } } } 

I expect that calling the foo method in a while loop will wait for the lock to be released (the locker area), but all calls to foo with arg of ++ I can go into the blocking block.

+7
source share
4 answers

The lock used here is reentrant. This will prevent another thread from entering the monitor, but the thread holding the lock will not be blocked.

+12
source

The lock keyword is just syntactic sugar around the Monitor.Enter and Monitor.Exit . As shown in the documentation for Monitor :

It is legal that the same thread calls Enter more than once without blocking it;

Calling lock(object) from the same thread more than once has no effect, except to increase the number of locks.

+7
source

Blocking does not apply if you are in the same thread. See http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx

+1
source

When you make a recursive call here in the say t1 thread, it does not unscrew a separate thread. A recursive call is made on the same thread t1.

Since t1 already holds the lock, it does not need to wait for the lock.

+1
source

All Articles