问题描述
我有一个包含3个静态成员的类.每个静态成员都不是线程安全的单例.我需要为它们的使用提供一个线程安全的实现,还是可以为它们每个提供线程安全的包装器?如果可以的话-如何使用Lazy<T>
做到这一点?
I have a class which has 3 static members. Each of static member is not thread-safe singleton.I need to provide a thread safe implementation for their use.Is it ok?Or I need to provide thread-safe wrapper for each of them? If I should - how can I do it using Lazy<T>
?
其他问题:SingeltonClass1/2/3
的Measure()
和Do()
不是线程安全的吗?func1()
线程安全的吗?
Additional question : Measure()
and Do()
of SingeltonClass1/2/3
are not thread-safe is func1()
thread-safe?
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
How should I re-implement MyLazySingleton if its constructor should get 2 arguments? string str
and int i
我问了一个后续问题单例类中的线程安全方法
推荐答案
它是线程安全的.
Lazy<T>
的LazyThreadSafetyMode
的默认值为ExecutionAndPublication
.
从 构造函数:
使用初始化的Lazy实例的线程安全模式 这个构造函数是LazyThreadSafetyMode.ExecutionAndPublication.
The thread safety mode of a Lazy instance that is initialized with this constructor is LazyThreadSafetyMode.ExecutionAndPublication.
如果您要使用另一个重载,您可以在其中传递不同 LazyThreadSafetyMode
值,但这不是线程安全的.但是像现在一样使用构造函数,它是线程安全的.
If you were to use another overload where you could pass a different LazyThreadSafetyMode
value it wouldn't be thread safe. But using the constructor as you are now, it is thread safe.
关于其他已编辑的问题,如果SingletonClass1
类型的那些方法不是 线程安全的:那么 no ,func1
也不是线程安全的
Regarding your additional edited question, if those methods on your SingletonClass1
type are not thread safe: then no, func1
is not thread safe either.
From the Lazy<T>
MSDN Page:
您将需要确保这些类之间的那些方法/交互是线程安全的.这个可能就像用lock
语句包装func1
正文一样简单,但是我不能确定地说,这取决于您SingletonClass1
的3个实例如何相互作用或如何相互作用.调用代码可以访问它们.
You will need to make sure that those methods/interactions between those classes are thread safe. This might be as simple as wrapping the func1
body with a lock
statement, but I can't say for certain depending on how your 3 instances of SingletonClass1
interact with each other or how calling code may access them.
这篇关于线程-安全的辛格尔顿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!