What is the best practice for using lock within inherited classes

Posted by JDMX on Stack Overflow See other posts from Stack Overflow or by JDMX
Published on 2010-05-21T15:01:40Z Indexed on 2010/05/21 15:40 UTC
Read the original article Hit count: 391

Filed under:
|
|
|

I want to know if one class is inheriting from another, is it better to have the classes share a lock object that is defined at the base class or to have a lock object defined at each inheritance level.

A very simple example of a lock object on each level of the class

public class Foo {
  private object thisLock = new object();
  private int ivalue;

  public int Value { 
    get {
      lock( thisLock ) {
        return ivalue;
      }
    }
    set {
      lock( thisLock ) {
        ivalue= value;
      }
    }
  }
}

public class Foo2: Foo {
  private object thisLock2 = new object();

  public int DoubleValue { 
    get {
      lock( thisLock2 ) {
        return base.Value * 2;
      }
    }
    set {
      lock( thisLock2 ) {
        base.Value = value / 2;
      }
    }
  }
}

public class Foo6: Foo2 {
  private object thisLock6 = new object();

  public int TripleDoubleValue { 
    get {
      lock( thisLock6 ) {
        return base.DoubleValue * 3;
      }
    }
    set {
      lock( thisLock6 ) {
        base.DoubleValue = value / 3;
      }
    }
  }
}

A very simple example of a shared lock object

public class Foo {
  protected object thisLock = new object();
  private int ivalue;

  public int Value { 
    get {
      lock( thisLock ) {
        return ivalue;
      }
    }
    set {
      lock( thisLock ) {
        ivalue= value;
      }
    }
  }
}

public class Foo2: Foo {     
  public int DoubleValue { 
    get {
      lock( thisLock ) {
        return base.Value * 2;
      }
    }
    set {
      lock( thisLock ) {
        base.Value = value / 2;
      }
    }
  }
}
public class Foo6: Foo2 {     
  public int TripleDoubleValue { 
    get {
      lock( thisLock ) {
        return base.DoubleValue * 3;
      }
    }
    set {
      lock( thisLock ) {
        base.DoubleValue = value / 3;
      }
    }
  }
}

Which example is the preferred way to manage locking within an inherited class?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about c#