Efficient pattern for multiple properties

I have an object that has about 15 properties, either String, decimal ?, DateTime? or int. I have a collection of this class that is managed from multiple threads. I would like to make sure that the property values โ€‹โ€‹of the objects are accessible (read / written) by a safe thread while writing the least amount of code. Is there such a way instead of using private proponents and explicitly blocking in the getter and setter of each individual property? Here's what I need to do for each property:

public class ManyProperties
{
    private Object mLock = new Object;
    private string _personName;
    public string PersonName {
        get {            
             lock (mLock){
                 return _personName;
             }           
        }
        set { 
             lock (mLock){
                  _personName = value; 
             }
        }
    }

    private string _beginAmount;
    public decimal? BeginAmount {
        get {            
             lock (mLock){
                 return _beginAmount;
             }           
        }
        set { 
             lock (mLock){
                  _beginAmount = value; 
             }
        }
    }
}

      

+3


source to share


1 answer


Properties usually don't work in isolation. Having every property thread-safe doesn't help unless you can get a correct and valid pair, etc. Values. A more appropriate approach is to make the whole thing immutable and let the caller get a snapshot :

public class ManyProperties
{
    private readonly string _personName;
    public string PersonName { get { return _personName; } }

    private readonly decimal? _beginAmount;
    public decimal? BeginAmount { get { return _beginAmount; } }

    public ManyProperties(string personName, string decimal? beginAmount) {
       _personName = personName;
       _beginAmount = beginAmount;
    }
}

      

then

var snapshot = whatever.Properties;
var name = snapshot.PersonName;
...
var amount = snapshot.BeginAmount;

      



Now they will always match . Plus there are zero locks. Reading / updating a reference is always atomic - so no dug values.

It is important not to do:

var name = whatever.Properties.PersonName;
...
var amount = whatever.Properties.BeginAmount;

      

because there is no longer any guarantee that name

they amount

came from the same instance ManyProperties

: someone could have changed the link between the two samples.

+4


source







All Articles