12.30.2008

Thread safe singleton pattern with C#: easy!

Read Here
Here is the classical manner 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;
}
}
}


摘要:以下這個優美的Thread-Safe Singleton實現基礎是.NET對運行期初始化的完整定義。它的優美之處是不需要典型的double-checked locking。

And now, the ".NET" way:

class Singleton
{
// Static members are lazily initialized.
// .NET guarantees thread safety for
// static initialization
private static readonly Singleton instance = new Singleton ();

// Constructor (private)
private Singleton () { }

public static Singleton 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?
  • 沒有留言: