I wrote simple code ( attached ) and i don’t understand why the lock on some block is not locking the scope.
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 the calling for the foo method in the while loop will be waiting until the locker will be release ( locker scope ) – but all the calls of the foo with arg of ++i can enter to the locker block.
The lock used here is reentrant. It will prevent another thread from entering the monitor, but the thread holding the lock will not be blocked.