private static readonly object Mutex = new object(); //this object has only 2 states -> lock or unlocked public static HighlanderThreadSafe GetInstance() { lock (Mutex) // this way only 1 thread can create a new instance of { if (_instance == null) { _instance = new HighlanderThreadSafe(); } return(_instance); } }
private static void SingletonThreadSafeExample() { //here we should try and make two thread create an instance at the same time. HighlanderThreadSafe john = HighlanderThreadSafe.GetInstance(); HighlanderThreadSafe rick = HighlanderThreadSafe.GetInstance(); Console.WriteLine($"john is equal to rick? {ReferenceEquals(john, rick)}"); HighlanderThreadSafeSimpler simpleJohn = HighlanderThreadSafeSimpler.Instance; HighlanderThreadSafeSimpler simpleRick = HighlanderThreadSafeSimpler.Instance; Console.WriteLine($"john is equal to rick? {ReferenceEquals(simpleJohn, simpleRick)}"); }