As per my understanding a lock is not released until the runtime completes the code block of the lock(obj) ( because when the block completes it calls Monitor.Exit(obj).
With this understanding i am not able to understand the reason behind the behaviour of the following code :
private static string obj = "";
private static void RecurseSome(int number)
{
Console.WriteLine(number);
lock (obj)
{
RecurseSome(++number);
}
}
//Call: RecurseSome(0)
//Output: 0 1 2 3...... stack overflow exception
There must be some concept that i am missing. Please help.
A lock knows which thread locked it. If the same thread comes again it just increments a counter and does not block.
So, in the recursion, the second call also goes in – and the lock internally increases the lock counter – because it is the same thread (which already holds the lock).
ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/dv_csref/html/656da1a4-707e-4ef6-9c6e-6d13b646af42.htm
Or MSDN: http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
states:
Note the thread references and the emphasis on “ANOTHER” thread.