///This is not Thread safe. when mutli threads try to call the ///GetSingletonObj, it can potentially ends up with multi instance public static SingletonCalss GetSingletonObj() { if (singletonobj == null) { singletonobj = new SingletonCalss(); } return(singletonobj); }
///This is Thread safe. But slows down the application public static SingletonCalss ThreadSafeGetSingletonObj() { lock (singletonobj) { if (singletonobj == null) { singletonobj = new SingletonCalss(); } return(singletonobj); } }
///This is Thread safe and only impacts creation public static SingletonCalss ThreadSafeGetSingletonObjV2() { if (singletonobj == null) { lock (singletonobj) { //Double check incase it got initialized while locking if (singletonobj == null) { singletonobj = new SingletonCalss(); } } } return(singletonobj); }
static void Main(string[] args) { SingletonCalss singleton = SingletonCalss.GetSingletonObj(); }