2

I understand its not recommended to use this for locks as the object can be modified outside of the class whcih is difficult to control. So, its always recommended to use private fields for locks. ( i have looked at : Why is lock(this) {...} bad? )

What about protected locks? i think i should be good as my classes are internal and no one can derive from them outside of my assembly...

Please note that i cannot use seperate locks derived and base class, as deadlock might occur as its difficult to manage in multiple classes.

internal class Base
{
    protected object sync = new object();
    public string Foo
    {
        get
        {
            lock (sync)
            {
                //set it
            }
        }
    }
}

internal class Derived : Base
{
    public string Bar
    {
        get
        {
            lock (sync)
            {
                //set it
                //try to  get "Foo" (if i use seperate locks-syncobjects
                // in derived and base class there can be a ptoential deadlock)
            }
        }
    }
}
Community
  • 1
  • 1
Dreamer
  • 3,371
  • 2
  • 34
  • 50

1 Answers1

0

You should use lock object for each field, I think it will solve your problem.

I you want to lock access to all field with the same lock object, I you suggest that you implement the lock mechanization in base class

Protected can cause the same problem as public since you dont know who will inherit from your class. for example if in get some value you want ot use some other field from the base class , you will fail.

So - protected is bad also

Mzf
  • 5,210
  • 2
  • 24
  • 37
  • 1
    It looks like "since you dont know who will inherit from your class" does not apply for this case - check Dreamer's: "no one can derive from them outside of my assembly". – Alexei Levenkov Jun 03 '13 at 05:36
  • You are right. Still I think this comment doesn't help when you are writing big code with maybe many people - it just error prone – Mzf Jun 03 '13 at 05:42