Daniel Hoelbling-Inzko talks about programming

Anatomy of a pattern: Singleton

Singleton is one of the simplest patterns that does just one thing: Ensure that there is one object to rule them all, one object to bind... (Ok sorry got dragged away).

The idea is simple: Sometimes (especially when writing to disk with open file handles) you need to ensure that there is only ONE instance of a class going on at any time. And that's it. It's so simple, you could turn it into a 1-liner:

public static Singleton _Instance;

But things never are that simple ;). By using only a shared variable you may end up calling the constructor twice, resulting in 2 objects that may get used by two different clients.

To avoid this you'll need to get an exclusive lock of the Singleton to ensure it's really empty before you instance it.
And that's how it's usually done

private static Singleton _Instance;
private static Object __LockObject = new object();

public static Singleton GetInstance() {     if (_Instance == null)     {         lock(__LockObject)         {             if (_Instance == null)                 _Instance = new Singleton();         }     }     return _Instance; }

In the singleton implementation the static Singleton variable holds the reference to the Singleton, and whenever we try to get a reference to this instance we check if it's already set and return the value.

If not, it get's tricky when 2 threads are getting a cache-miss at the exact same time (_Instance == null). If you aren't synchronizing at this point you may end up with two different references of a singleton object being used (and causing problems with resources being consumed twice, causing ). So it's important to perform another check when you have exclusive reign over the shared object (by using a lock object here).

This ensures that no two threads will try to create a new instance to your singleton, while not slowing down your read-performance at all.

Sample code: Singleton.cs

My Photography business


dynamic css for .NET