static void Main(string[] args) { Singleton obj1 = Singleton.Instance; Singleton obj2 = Singleton.Instance; if (obj1 == obj2) { Console.WriteLine("SingleTon Successful"); } ThreadSafeSingleton obj3 = ThreadSafeSingleton.Instance; ThreadSafeSingleton obj4 = ThreadSafeSingleton.Instance; if (obj3 == obj4) { Console.WriteLine("SingleTon Successful"); } LazySingleton obj5 = LazySingleton.Instance; LazySingleton obj6 = LazySingleton.Instance; if (obj5 == obj6) { Console.WriteLine("SingleTon Successful"); } }
public static ThreadSafeSingleton GetInstance() { lock (_lock) { if (_instance == null) { if (_isFirstThread) { _isFirstThread = false; Thread.Sleep(1000); } _instance = new ThreadSafeSingleton(); } } return(_instance); }
static void Main(string[] args) { var singletonA = Singleton.Instance; var singletonB = Singleton.Instance; Console.WriteLine("singletonA: " + singletonA.GetHashCode()); Console.WriteLine("singletonB: " + singletonB.GetHashCode()); ThreadSafeSingleton threadSafeX; ThreadSafeSingleton threadSafeY; Task <ThreadSafeSingleton> getX = ThreadSafeSingleton.GetInstanceAsync(); Task <ThreadSafeSingleton> getY = ThreadSafeSingleton.GetInstanceAsync(); Task.WaitAll(getX, getY); threadSafeX = getX.Result; threadSafeY = getY.Result; Console.WriteLine("threadSafeX: " + threadSafeX.GetHashCode()); Console.WriteLine("threadSafeY: " + threadSafeY.GetHashCode()); }