public sealed class Singleton
{
private Singleton() {}
private static volatile Singleton _value;
private static object syncRoot = new Object();
public static Singleton Value
{
get
{
if (_value == null)
{
lock (syncRoot)
{
if (_value == null)
{
_value = new Singleton();
} //end inner if
} //end lock
} //end outer if
return _value;
} //end get
} //end Value
} //end class
• Double-check locking is used to ensure that exactly one instance is ever created and only when needed
• syncRoot is used to lock on rather than locking on the type itself to avoid deadlocks caused by outside code
• The _value instance is declared to be volatile in order to assure that the assignment to _value and any writes inside the Singleton constructor complete before the instance can be accessed
博客展示了一个用C#实现的单例模式代码。通过定义私有构造函数、静态变量和锁机制,确保在多线程环境下单例对象的创建是线程安全的,避免了重复创建单例对象的问题。
444

被折叠的 条评论
为什么被折叠?



