static void Main(string[] args) { //Simple Singleton SimpleSingleton simpleSingleton = SimpleSingleton.GetInstance(); simpleSingleton.ShowMessage("simple singleton"); SimpleSingleton simpleSingleton2 = SimpleSingleton.GetInstance(); if (simpleSingleton == simpleSingleton2) { Console.WriteLine("This is the same instance"); } //Thread Safe Singleton, call from the master thread ThreadSafeSingleton threadSafeSingleton = ThreadSafeSingleton.GetInstance(); threadSafeSingleton.ShowMessage("thread safe singleton"); ThreadSafeSingleton threadSafeSingleton2 = ThreadSafeSingleton.GetInstance(); if (threadSafeSingleton == threadSafeSingleton2) { Console.WriteLine("This is the same instance"); } //Get object from different threads. Parallel.For(0, 10000, (i) => { ThreadSafeSingleton threadSingleton = ThreadSafeSingleton.GetInstance(); ThreadSafeSingleton threadSingleton2 = ThreadSafeSingleton.GetInstance(); if (threadSingleton != threadSingleton2) { throw new Exception("The threads broke the program"); } }); }
//a helper method designed to set the singleton to null which triggers a rebuilding of the instance on next use public void Clear() { Console.WriteLine("Clearing singleton..."); //by setting this to null, the next thread that uses this singleton will cause it to reinitialize _instance = null; }
public static ThreadSafeSingleton getInstance() { if (instance == null) { instance = new ThreadSafeSingleton(); } return(instance); }
static void Main(string[] args) { Singleton s1 = Singleton.SingleInstance; Singleton s2 = Singleton.SingleInstance; Singleton s3 = Singleton.SingleInstance; ThreadSafeSingleton tss1 = ThreadSafeSingleton.SingleInstance; ThreadSafeSingleton tss2 = ThreadSafeSingleton.SingleInstance; ThreadSafeSingleton tss3 = ThreadSafeSingleton.SingleInstance; Console.ReadKey(); }
public static ThreadSafeSingleton GetInstance() { lock (padLock) { if (_instace == null) { _instace = new ThreadSafeSingleton(); } return(_instace); } }
static void Main(string[] args) { // Lazy Initialization Singleton Design Pattern LazyInitializationSingleton lazyInitializationSingleton = LazyInitializationSingleton.GetInstance(); lazyInitializationSingleton.TestInstance(); // Eager Initialization Singleton Design Pattern EagerInitializationSingleton eagerInitializationSingleton = EagerInitializationSingleton.GetInstance(); eagerInitializationSingleton.TestInstance(); // Thread Safe Singleton Design Pattern ThreadSafeSingleton threadSafeSingleton = ThreadSafeSingleton.GetInstance(); threadSafeSingleton.TestInstance(); }