Thread safe Singleton in C#
2005-06-15 16:27
375 查看
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
{
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
相关文章推荐
- Custom ThreadPool in Java to Perform as ThreadPool in C# based on Singleton Model
- My Singleton in C#
- 【转】单体模式-经典实现 Implementing the Singleton Pattern in C#
- Implementing the Singleton Pattern in C#
- Singleton in C#
- [收藏]IOCP Thread Pooling in C#
- Implementing Singleton in C#
- Implementing the Singleton Pattern in C#
- 《C++ Concurrency in Action》笔记15 a thread-safe queue with condition variable
- C#中线程的使用[Thread in C#]
- Implementing the Singleton Pattern in C#
- Thread Safe In Servlet
- 依旧是转载来的Thread and Sync In C# (C#中的线程与同步)
- Implementing the Singleton Pattern in C#
- IOCP Thread Pooling in C#
- Singleton Pattern in C# 5种实现
- Implementing the Singleton Pattern in C#
- thread safe lazy initialization singleton
- Thread and Sync In C# (C#中的线程与同步)
- Implementing the Singleton Pattern in C#