using System; namespaceSingletonPatternDemo { sealedclassSingleton { privateSingleton() { }
privatestatic Singleton _instance;
privatestaticreadonlyobject _lock = newobject();
publicstatic Singleton GetInstance(stringvalue) { if (_instance == null) { lock (_lock) { if (_instance == null) { _instance = new Singleton(); _instance.Value = value; } } } return _instance; }
publicstring Value { get; set; } }
classProgram { staticvoidMain(string[] args) { Console.WriteLine( "{0}\n{1}\n\n{2}\n", "If you see the same value, then singleton was reused (yay!)", "If you see different values, then 2 singletons were created (booo!!)", "RESULT:" );
Thread process1 = new Thread(() => { TestSingleton("FOO"); }); Thread process2 = new Thread(() => { TestSingleton("BAR"); });