public static void TestSingletonThreadSafe() { Console.Clear(); Console.WriteLine("TestSingletonThreadSafe"); Thread process1 = new Thread(() => { SingletonThreadSafe s1 = SingletonThreadSafe.GetInstance("Foo"); Console.WriteLine(s1.Value); //Singleton s1 = Singleton.GetInstance(); //s1.SomeBusinessLogic(); }); Thread process2 = new Thread(() => { SingletonThreadSafe s2 = SingletonThreadSafe.GetInstance("bar"); Console.WriteLine(s2.Value); //Singleton s2 = Singleton.GetInstance(); //s2.SomeBusinessLogic(); }); process1.Start(); process2.Start(); process1.Join(); process2.Join(); Wait(); }
public static SingletonThreadSafe getInstance() { lock (typeof(SingletonThreadSafe)) { if (instance == null) { instance = new SingletonThreadSafe(); } } return(instance); }
public static SingletonThreadSafe GetSingleton() { lock (singletonLock) // a thred needs to aquire the lock to execute below code { if (singleton == null) { singleton = new SingletonThreadSafe(); } return(singleton); } }
public static SingletonThreadSafe GetInstance() { lock (objSync) { if (theInstance == null) { theInstance = new SingletonThreadSafe(); } return(theInstance); } }
public static SingletonThreadSafe GetInstance() { lock (lockObj) { if (_instance == null) { _instance = new SingletonThreadSafe(); } } return(_instance); }
public static SingletonThreadSafe getInstance() { if (instance == null) { lock (lockObj) { if (instance == null) { instance = new SingletonThreadSafe(); count++; } } } return(instance); }
private static void CheckEquality(SingletonThreadSafe singleton1, SingletonThreadSafe singleton2) { if (singleton1 == singleton2) { Console.WriteLine("=="); } if (singleton1.Equals(singleton2)) { Console.WriteLine("equals"); } if (object.ReferenceEquals(singleton1, singleton2)) { Console.WriteLine("ReferenceEquals\n"); } }
static void Main(string[] args) { var singleton1 = SingletonThreadSafe.GetSingleton(); var singleton2 = SingletonThreadSafe.GetSingleton(); CheckEquality(singleton1, singleton2); var singleton3 = SingletonLazyThreadSafe.GetSingleton().Value; var singleton4 = SingletonLazyThreadSafe.GetSingleton().Value; CheckEquality(singleton3, singleton4); var singleton5 = new SingletonLazyThreadSafe(); CheckEquality(singleton4, singleton5); // Should not print anything as it vioaltes singleton Console.ReadKey(); }
public static void setNullInstance() { instance = null; }