c# - Making class fields thread-safe -
say have list
of values accessed different threads. make thread safe doing this:
private static object syncobject; syncobject = new object(); public list<double> mylist { { lock(syncobject) { return mylist;} } set { lock(syncobject) { mylist = value;} } }
if in 1 of functions, need access count
attribute of list
, may not thread safe anymore. how write such when accessing attributes, thread safe?
like willem van rumpt said, synchronized access specific property, not made thread safe. not reinvent wheel, can use collections system.collections.concurrent (https://msdn.microsoft.com/en-us/library/dd267312(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1)
another more viable option use immutable list. unfortunately, afaik .net doesn't offer here. implementation know in microsoft.fsharp.collections. list in namespace immutable singly-linked list. (although haven't used c#).
update: matÃas fidemraizer noted, there system.collections.immutable nuget package available .net 4.5 , above contains implementations multiple immutable collections. thank you!
Comments
Post a Comment