Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# lock object inside instance object

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?

like image 948
amir110 Avatar asked Jul 24 '26 14:07

amir110


1 Answers

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
        }
    }
}
like image 84
Steven Avatar answered Jul 27 '26 02:07

Steven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!