Thread safe singleton pattern with C#: easy!
Read here: http://www.dofactory.com/Patterns/PatternSingleton.aspx
Here is the classical maneer a thread-safe singleton is written in C#:
class MySingleton
{
private static MySingleton instance;
// Lock synchronization object
private static object syncLock = new object();
private MySingleton() { DoSomething(); }
public static MySingleton Instance
{
get
{
// Support multithreaded applications
// through 'Double checked locking'
// pattern which (once the instance
// exists) avoids locking each
// time the method is invoked
if (instance == null)
{
lock (syncLock)
{
if (instance == null)
instance = new MySingleton();
}
}
return instance;
}
}
}
And now, the ".NET" way:
class MySingleton
{
// Static members are lazily initialized.
// .NET guarantees thread safety for
// static initialization
private static readonly MySingleton instance =
new MySingleton();
// Constructor (private)
private MySingleton() { DoSomething(); }
public static Instance { get { return instance; } }
}
This works because "private static readonly" involves:
- lazy initialization
- thread safety guaranteed by .NET for static initializations.
Ain't it beautiful?