C# Singleton pattern with triggerable initialization

前端 未结 6 1783
遥遥无期
遥遥无期 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:03

    public class Singleton where T : class, new()
    {
        private static T instance;
        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    throw new Exception("singleton needs to be initialised before use");
                }
                return instance;
            }
        }
        public static void Initialise(Action initialisationAction)
        {
            lock(typeof(Singleton))
            {
                if (instance != null)
                {
                    return;
                }
                instance = new T();
                initialisationAction(instance);
            }
        }
    }
    

提交回复
热议问题