i faced ith situation that force me to lock a lock object that is inside of instance object i want to know is it true or not?
for clarify :
public class classA
{
object objLock = new object();
public void MethodA(object objClassA)
{
classA cls = (classA)objClassA;
lock(cls.objLock)
{
Do something with cls
}
}
}
is it allowed to do it?
The object you lock on is in the same class, but a different instance. In that sense you are not breaking encapsulation, but you should still prefer extracting that code so you can prevent locking on an external object. Here's an example:
public class classA
{
private readonly object objLock = new object();
public void MethodA(object objClassA)
{
classA cls = (classA)objClassA;
cls.DoSomething();
}
private void DoSomething()
{
lock (this.objLock)
{
Do something with cls
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With