amir110
amir110

Reputation: 33

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?

Upvotes: 3

Views: 1388

Answers (2)

Steven
Steven

Reputation: 172786

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
        }
    }
}

Upvotes: 5

parapura rajkumar
parapura rajkumar

Reputation: 24413

This is perfectly fine. It is legal C#. In fact this is the preferred way instead of locking this. Because this can be locked from outside the class whereas objLock being private can only be locked within the class, giving you better control and avoiding some deadlock conditions

However the casting could potentially throw an exception. You might want to handle that scenario

Upvotes: 2

Related Questions