title: C# Singleton pattern with triggerable initialization
body: <p>I need a singleton that:</p>
  
  <ul>
  <li>is lazy loaded</li>
  <li>is thread safe</li>
  <li>loads some values at construction</li>
  <li>those values can be queried at any time</li>
  <li>the initialization MAY happen at some precise time, before the querying begins - so I must be able to trigger it from the outside somehow. Of course, triggering multiple times should only do the initialization once.</li>
  </ul>
  
  <p>I use .NET 3.5.</p>
  
  <p>I've started with Jon Skeet's <a href="http://csharpindepth.com/Articles/General/Singleton.aspx" rel="nofollow">implementation</a> (5th version) using a static subclass: </p>
  
  <pre><code>public sealed class Singleton
  {
      IEnumerable&lt;string&gt; Values {get; private set;}
      private Singleton()
      {
          Values = new[]{"quick", "brown", "fox"};
      }
  
      public static Singleton Instance { get { return Nested.instance; } }
  
      private class Nested
      {
          // Explicit static constructor to tell C# compiler
          // not to mark type as beforefieldinit
          static Nested()
          {
          }
  
          internal static readonly Singleton instance = new Singleton();
      }
  } 
  </code></pre>
  
  <p>This ticks almost all the boxes, except the "trigger initialization from outside". Since the actual initialization happens inside the ctor, it can't happen more than once.</p>
  
  <p>How can this be accomplished? </p>
  
  <p>The singleton will be used like this: </p>
  
  <pre><code>public static void Main(){
  
      //do stuff, singleton should not yet be initialized.
  
      //the time comes to initialize the singleton, e.g. a database connection is available
      //this may be called 0 or more times, possibly on different threads
  
      Singleton.Initialize();
      Singleton.Initialize();
      Singleton.Initialize();
  
      //actual call to get retrieved values, should work
      var retrieveVals = Singleton.Instance.Values;
  
  }
  </code></pre>