Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do static locks work across different children classes?

If I have

abstract class Parent
{
    static object staticLock = new object();

    public void Method1()
    {
        lock(staticLock)
        {
            Method2();
        }
    }

    protected abstract Method2();
}

class Child1 : Parent
{
    protected override Method2()
    {
          // Do something ...
    }
}

class Child2 : Parent
{
    protected override Method2()
    {
          // Do something else ...
    }
}

Will calls to new Child1().Method1() and new Child2().Method1() use the same lock?

like image 568
Jader Dias Avatar asked Feb 08 '12 17:02

Jader Dias


3 Answers

Yes. A derived class does not get a new copy of the static data from the base class.

However, this is not the case with generic classes. If you say:

class Base<T>
{
    protected static object sync = new object();
    ...
}

class Derived1 : Base<int> { ... }
class Derived2 : Base<int> { ... }
class Derived3 : Base<string> { ... }
class Derived4 : Base<string> { ... }
class Derived5 : Base<object> { ... }
class Derived6 : Base<object> { ... }

instances of Derived1 and Derived2 have the same sync object. Instances of Derived3 and Derived4 have the same sync object. Instances of Derived5 and Derived6 have the same sync object. But the three sync objects are all different objects.

like image 187
Eric Lippert Avatar answered Nov 10 '22 17:11

Eric Lippert


Yes, generally speaking, lock on static objects protect data for all instances of your class.

From MSDN:

Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.

like image 26
ken2k Avatar answered Nov 10 '22 16:11

ken2k


To add to ken2k's answer: [Yes] ... unless it's marked as [ThreadStatic] (which obviously isn't the case here).

like image 35
sunside Avatar answered Nov 10 '22 16:11

sunside