I wrote a piece of code about singleton pattern implementation. Not sure its correctness. Please give some advice. Thanks.
public class Singleton
{
public Singleton Instance
{
get
{
if (_instance == null)
{
if (_mutexCreation.WaitOne(0))
{
try
{
if (_instance == null)
{
_instance = new Singleton();
}
}
finally
{
_mutexCreation.ReleaseMutex();
开发者_StackOverflow _eventCreation.Set();
}
}
else
{
_eventCreation.WaitOne();
}
}
return _instance;
}
}
private Singleton() { }
private static Singleton _instance;
private static Mutex _mutexCreation = new Mutex();
private static ManualResetEvent _eventCreation = new ManualResetEvent(false);
}
public class Singleton
{
private static object _syncRoot = new object();
public Singleton Instance
{
get
{
if (_instance == null)
{
lock (_syncRoot)
{
if (_instance != null)
return _instance;
_instance = new Singleton();
}
}
return _instance;
}
}
private Singleton() { }
private static Singleton _instance;
}
If you do not want to use lazy loading, simply create a new instance directly in a static constructor.
精彩评论