Singleton Pattern in C#

See this site: http://www.yoda.arachsys.com/csharp/singleton.html

This is the basic singleton pattern in C#. It works but isn't thread safe.

// This is not thread safe!
public sealed class Singleton
{
    static Singleton instance=null;
 
    Singleton()
    {
    }
 
    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

I chose the second version from that site, which uses a lock to ensure thread safety.

public sealed class Singleton
{
    static Singleton instance = null;
    static readonly object padlock = new object();
 
    Singleton()
    {
    }
 
    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance==null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

Note that both of these use lazy instantiation. That is, the singleton instance isn't created until the first time the Instance property is called.

 
software_development/dotnet/singleton.txt · Last modified: 2008/04/08 12:10 (external edit)
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki