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.
Lock doesn't apply if you are on the same thread. See http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
The lock keyword is just syntactic sugar around the Monitor.Enter
and Monitor.Exit
methods. As seen in the documentation for Monitor
:
It is legal for the same thread to invoke Enter more than once without it blocking;
Calling lock(object)
from the same thread more than once has no effect other than to increase the lock count.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With