.net - Thread safe pattern for multiple properties -
i have object has 15 properties of either string, decimal?, datetime? or int?. have collection of of class manipulated multiple threads. create sure values of objects' properties accessed (read/written) in thread safe manner, while writing to the lowest degree amount of code. there such way instead of using private backers , doing explicit lock in getter , setter of every single property? here have each property:
public class manyproperties { private object mlock = new object; private string _personname; public string personname { { lock (mlock){ homecoming _personname; } } set { lock (mlock){ _personname = value; } } } private string _beginamount; public decimal? beginamount { { lock (mlock){ homecoming _beginamount; } } set { lock (mlock){ _beginamount = value; } } } }
properties not work in isolation. having each property thread-safe doesn't help if can't right , valid pair etc of values. more appropriate approach create entire thing immutable, , allow caller snapshot:
public class manyproperties { private readonly string _personname; public string personname { { homecoming _personname; } } private readonly decimal? _beginamount; public decimal? beginamount { { homecoming _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;
these always consistent. plus there 0 locks. reading / updating reference atomic, - no torn values.
the of import thing not do:
var name = whatever.properties.personname; ... var amount = whatever.properties.beginamount;
because here there no longer guarantee name
, amount
came same manyproperties
instance: have swapped reference between 2 fetches.
.net multithreading properties thread-safety
No comments:
Post a Comment