Monday, February 11, 2008

Creating a Thread-Safe Singleton

Developer.com - .NET Tip: Creating a Thread-Safe Singleton

"A singleton is used to ensure that there is only one instance of a class created. A singleton also provides the single point of access to that one instance of the class. Singletons can be used for a wide range of reasons, from a better means of managing global variables to creating abstract factories to maintaining a state machine for you application. Regarless of your use of the singleton, I will show you how to create a bare-bones singleton that can be created in a thread-safe manner. Here is the code:

public sealed class Singleton
{
private static Singleton _Instance = null;
private static readonly object _Lock = new object();

private Singleton()
{
}

public static Singleton Instance
{
get
{
lock (_Lock)
{
if (_Instance == null)
_Instance = new Singleton();

return _Instance;
}
}
}
}


First, the class is marked as sealed so..."




I thought this was a pretty cool tip and didn't want to lose it...



(via Shared Points... - Thread safe singleton)

2 comments:

Jay R. Wren said...

or....

don't create singletons. Seriously, you don't need it.

Use Windsor or another IoC to manage your instances for you. Thread-safe singletons by default. Converted to transient objects by flipping a configuration switch.

blorq said...

This is a very flawed methodolgy. You do _not_ want to lock on get every time. That would not perform well at all.

Try this instead:
public class Singleton<T> where T : class, new ( )
{
Singleton(){}

class SingletonCreator
{
static SingletonCreator(){}
//private object instantiated with private constructor
internal static readonly T instance = new T();
}

public static T Instance
{
get { return SingletonCreator.instance; }
}

}

Useage: Singleton<MyClass>.Instance. It lazy loads on the first use of the assembly.