我有一个有3个静态成员的类。每个静态成员不是线程安全的单例。 我需要为它们的使用提供一个线程安全的实现。它可以吗?或者我需要为它们中的每一个提供线程安全的包装?如果我应该 - 我如何使用Lazy<T>
做到这一点?线程安全singelton
附加问题:Measure()
和Do()
of SingeltonClass1/2/3
不是线程安全的func1()
线程安全吗?
public class MyLazySingleton
{
// static holder for instance, need to use lambda to construct since constructor private
private static readonly Lazy<MyLazySingleton> _instance
= new Lazy<MyLazySingleton>(() => new MyLazySingleton());
// private to prevent direct instantiation.
private MyLazySingleton()
{
s_c1 = SingletonClass1.Instance();
s_c2 = SingletonClass2.Instance();
s_c3 = SingletonClass3.Instance();
}
// accessor for instance
public static MyLazySingletonInstance
{
get
{
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;
}
如何重新实现MyLazySingleton如果它的构造函数应该得到2个参数? string str
和int i
我曾问一个跟进的问题Thread-safe methods in the singleton class
我编辑了我的答案,包括您的额外编辑/问题。如果您还有其他问题,可能有新的针对性问题。 –
我没有注意到您编辑的底部的第三个问题。您打算如何提供这些参数会影响答案。我建议你创建一个新的问题_specifically_关于这一点。 (是参数编译时常量吗?你会更新你的'MyLazySingletonInstance'来传递它们吗?用户会以某种方式指定它们吗?等等) –