C# Singleton pattern with triggerable initialization

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

    The first idea I had was to just use a throwaway variable assigned to the singleton's instance, which would (probably?) trigger the initialization

    static Main() 
    {
        var unused = Singleton.Instance;
        //this should initialize the singleton, unless the compiler optimizes it out.
        //I wonder if the compiler is smart enough to see this call has side effects.
    
        var vals = Singleton.Instance.Values;
    }
    

    ... but programming by side-effects is something I try hard to avoid, so let's make the intention a bit clearer.

    public class Singleton {
        public static void Initialize() {
            //this accesses the static field of the inner class which triggers the private Singleton() ctor.  
            Instance._Initialize();
        }
        private void _Initialize()
        { //do nothing
        }
    
        [the rest as before]
    }
    

    so the usage would be:

    static Main() 
    {
        //still wondering if the compiler might optimize this call out
        Singleton.Initialize();
    
        var vals = Singleton.Instance.Values;
    }
    

    Btw this would also work:

    static Main() 
    {
        var vals = Singleton.Instance.Values;
    }
    

    Compiler optimization aside, I think this deals with all the requirements.

提交回复
热议问题