Thread safe Singleton in C#

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

Published At
Categories with Web编程
Tagged with
comments powered by Disqus