Possible Duplicate:
Re-entrant locks in C#
I've looked here on StackOverflow and on MSDN, and can't believe that I couldn't find this question lingering out there on the internets.
Let's say I have a class with a private member that I want to access in several public methods. These public methods will be called by different threads, hence the need for synchronization.
public class MyClass
{
private Object SomeSharedData = new Object();
public void MethodA()
{
lock( SomeSharedData) {
// do something
MethodB();
}
}
public void MethodB()
{
lock( SomeSharedData) {
// do something
}
}
}
Note that MethodA and MethodB can be called by users of this class, but MethodA also calls MethodB, which results in a nested locking condition.
Is this guaranteed to be safe? In other words, does .NET handle this by reference counting the lock, so that as I pop out of these methods, the lock gets decremented? Or is .NET performing some magic behind the scenes, whereby it simply ignores all subsequent locks on the object originating from the same thread?