Reputation: 355
I've been researching nested and multiple locks, but I haven't found where this specific scenario has been addressed.
class x
{
Method1()
{
Lock (object)
{
Method2();
}
}
Method2()
{
Lock (object)
{
//do stuff
}
}
}//close class x
Can the lock objects be the same or do they have to be different?
Is there an advantage of one approach over the other?
Upvotes: 3
Views: 363
Reputation: 564403
They can be the same, since lock
(Monitor) is reentrant in .NET.
This is mentioned in the documentation for Monitor.Enter:
It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.
Since the same thread can enter the lock using the same object more than once, the above code will work fine sharing the same synchronization object.
Upvotes: 6