C# Singleton pattern with triggerable initialization

前端 未结 6 1785
遥遥无期
遥遥无期 2021-02-09 09:45

I need a singleton that:

  • is lazy loaded
  • is thread safe
  • loads some values at construction
  • those values can be queried at any time
6条回答
  •  花落未央
    2021-02-09 10:05

    You can do something like this

    public sealed class Singleton
    {
        IEnumerable Values { get; set; }
    
        private Singleton()
        {
            Console.WriteLine("-- Private Singleton constructor");
            Values = new[] { "quick", "brown", "fox" };
        }
    
        public static Singleton Instance
        {
            get
            {
                Console.WriteLine("- Singleton Instance");
                return Nested.instance;
            }
        }
    
        public static void Initialize()
        {
            Console.WriteLine("- Singleton Initialize");
            Nested.Initialize();
        }
    
        internal class Nested
        {
            private static object syncRoot = new object();
            // Explicit static constructor to tell C# compiler
            // not to mark type as beforefieldinit
            static Nested()
            {
                Console.WriteLine("-- Static Nested constructor");
            }
    
            internal static readonly Singleton instance = new Singleton();
    
            internal static void Initialize()
            {
                lock (syncRoot)
                {
                    Console.WriteLine("-- Locked");
                    Console.WriteLine("--- Nested Initialize");
                    Console.WriteLine("-- Unlocked");
                }
            }
        }
    }
    

    Usage

    class Program
    {
        static void Main(string[] args)
        {
            var i = Singleton.Instance;
            i = Singleton.Instance;
    
            Console.WriteLine("-----");
    
            Singleton.Initialize();
            Singleton.Initialize();
            Singleton.Initialize();
    
            Console.Read();
        }
    }
    

    Which outputs

    - Singleton Instance
    -- Private Singleton constructor
    -- Static Nested constructor
    - Singleton Instance
    -----
    - Singleton Initialize
    -- Locked
    --- Nested Initialize
    -- Unlocked
    - Singleton Initialize
    -- Locked
    --- Nested Initialize
    -- Unlocked
    - Singleton Initialize
    -- Locked
    --- Nested Initialize
    -- Unlocked
    

提交回复
热议问题