c# - Thread - safe singelton -
i have class has 3 static members. each of static member not thread-safe singleton. need provide thread safe implementation use.is ok?or need provide thread-safe wrapper each of them? if should - how can using lazy<t>
?
additional question : measure()
, do()
of singeltonclass1/2/3
not thread-safe func1()
thread-safe?
public class mylazysingleton { // static holder instance, need use lambda construct since constructor private private static readonly lazy<mylazysingleton> _instance = new lazy<mylazysingleton>(() => new mylazysingleton()); // private prevent direct instantiation. private mylazysingleton() { s_c1 = singletonclass1.instance(); s_c2 = singletonclass2.instance(); s_c3 = singletonclass3.instance(); } // accessor instance public static mylazysingletoninstance { { return _instance.value; } } public void func1() { if (s_s1.measure() || s_c2.measure()) { c_c3.do(); } } static singletonclass1 s_c1 = null; static singletonclass1 s_c2 = null; static singletonclass1 s_c3 = null; }
how should re-implement mylazysingleton if constructor should 2 arguments? string str
, int i
i have asked follow question thread-safe methods in singleton class
it's thread-safe is.
the default value lazy<t>
's lazythreadsafetymode
executionandpublication
.
from msdn page on new lazy<t>(func<t>)
constructor:
an instance created constructor may used concurrently multiple threads.
the thread safety mode of lazy instance initialized constructor lazythreadsafetymode.executionandpublication.
if use another overload pass different lazythreadsafetymode
value wouldn't thread safe. using constructor now, thread safe.
edit: regarding additional edited question, if methods on singletonclass1
type not thread safe: no, func1
not thread safe either.
from lazy<t>
msdn page:
making lazy object thread safe not protect lazily initialized object. if multiple threads can access lazily initialized object, must make properties , methods safe multithreaded access.
you need make sure methods/interactions between classes thread safe. might simple wrapping func1
body lock
statement, can't depending on how 3 instances of singletonclass1
interact each other or how calling code may access them.
Comments
Post a Comment