As others already noted, the lock is helt by the thread and will therefore work. However, I want to add something to this.
Joe Duffy, a concurrency specialist from Microsoft, has multiple design rules about concurrency. One of his design rules state:
9 . Avoid lock recursion in your design. Use a non-recursive lock
where possible.
Recursion typically indicates an over-simplification in your
synchronization design that often
leads to less reliable code. Some
designs use lock recursion as a way to
avoid splitting functions into those
that take locks and those that assume
locks are already taken. This can
admittedly lead to a reduction in code
size and therefore a shorter
time-to-write, but results in a more
brittle design in the end.
(source)
To prevent the recursive lock, rewrite the code to the following:
private readonly static object obj = new object();
private static void Some(int number)
{
lock (obj)
{
RecurseSome(number);
}
}
private static void RecurseSome(int number)
{
Console.WriteLine(number);
RecurseSome(++number);
}
Furthermore, I your code will throw a StackOverflowException
, because it never ends recursively calling itself. You could rewrite your method as follows:
private static void RecurseSome(int number)
{
Console.WriteLine(number);
if (number < 100)
{
RecurseSome(++number);
}
}