C# Singleton pattern with triggerable initialization

前端 未结 6 1761
遥遥无期
遥遥无期 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 use double-checked locking pattern. Just add following code in you Singleton class:

    public sealed class Singleton
    {
       ..........................
    
            private static object locker = new object();
            private static bool initialized = false;
    
            public static void Initialize() {
               if (!initialized){ 
                 lock(locker) {
                    if (!initialized){ 
                      //write initialization logic here
                      initialized = true;
                     }
                  }
                }
            }
    
    .......................
    
    }
    

提交回复
热议问题