Tech Off Post

Single Post Permalink

View Thread: Thread Safe Singleton Pattern - C# ???
  • User profile image
    offwhite

    Use a private method with an attribute to handle the locking to create the instance.

    public static Singleton Instance
    {
      get
      {
        if (_instance == null)
        {
          InstantiateSingleton();
        }
        return _instance;
      }
    }

    // requires using System.Runtime.CompilerServices
    [MethodImpl(MethodImplOptions.Synchronized)]
    private static void InstantiateSingleton()
    {
      if (_singleton == null)
      {
        _singleton = new Singleton();
      }
    }