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:

  1. 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.

    ReplyDelete
  2. 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.

    ReplyDelete

NOTE: Anonymous Commenting has been turned off for a while... The comment spammers are just killing me...

ALL comments are moderated. I will review every comment before it will appear on the blog.

Your comment WILL NOT APPEAR UNTIL I approve it. This may take some hours...

I reserve, and will use, the right to not approve ANY comment for ANY reason. I will not usually, but if it's off topic, spam (or even close to spam-like), inflammatory, mean, etc, etc, well... then...

Please see my comment policy for more information if you are interested.

Thanks,
Greg

PS. I am proactively moderating comments. Your comment WILL NOT APPEAR UNTIL I approve it. This may take some hours...