Wednesday, January 6, 2010

Implementation of thread safe Singleton in C#

Lazy initialization

public sealed class Singleton
{
    static Singleton instance=null;
    static readonly object instancelock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (instancelock)
            {
                if (instance==null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

Thread-safe without locks
public sealed class Singleton
{
    static readonly Singleton instance=new Singleton();

    static Singleton()
    {
    }

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

No comments: