How to

implement thread safe Singleton

Published: 1. February 2012 | Updated: 1. February 2012
License: Microsoft Public License (MS-PL)
Categories: Implementations
Tags: C# Design Patterns Threading
Was this snippet helpful for you? YESYES / NONO

Implementation

public sealed class Singleton
{
    private static volatile Singleton _instance;
    private static readonly object Lock = new object();

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

    private Singleton()
    {

    }
}

Use

var instance = Singleton.Instance;
Send us feedback about this snippet »



Related Snippets: