// Create a static method for object creation //With double-checking it ok but lock kills the performance public static MyRepoSingletonThreadSafe GetInstance() { // Only instantiate the object when needed. if (uniqueInstance == null) { Thread.Sleep(5); //to simulate access by multithread lock (myLock) { if (uniqueInstance == null) { Console.WriteLine("A singleton has been created"); uniqueInstance = new MyRepoSingletonThreadSafe(); } } } return(uniqueInstance); }
//MyRepoSingletonNotThreadSafe -> run it 5 or 6 time to see random behaviour (write one or two messages) //MyRepoSingletonThreadSafe -> Always two messages private static MyRepoSingletonThreadSafe MyRepo() { return(MyRepoSingletonThreadSafe.GetInstance()); }