Yes lock(a){}
is equivalent to lock(b){}
.
The lock() documentation states that the lock statement marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object of reference type.
a
and b
are both the same object so yes they are equivalent. Actually a
and b
are both references to the same object.
A cast operation between reference types does not change the run-time type of the underlying object; it only changes the type of the value that is being used as a reference to that object. Source.
A quick test program shows that it does indeed behave the way it is documented:
namespace ConsoleApplication2
{
public class A { }
public class B : A { }
class Program
{
static A a = new B();
static void MyThread()
{
B b = a as B;
lock (b)
{
Console.WriteLine("b lock acquired");
Console.WriteLine("releasing b lock");
}
}
static void Main(string[] args)
{
System.Threading.Thread t = new System.Threading.Thread(MyThread);
lock(a)
{
Console.WriteLine("a lock acquired");
t.Start();
System.Threading.Thread.Sleep(10000);
Console.WriteLine("Releasing a lock");
}
}
}
}
a lock acquired
... 10 seconds pass
releasing a lock
b lock acquired
releasing b lock