//多執行緒時保證SingletonLock一定是單一的 public static SingletonLock GetSingletonLock() { if (instance == null) { lock (SingletonLock.instance) { if (instance == null) { instance = new SingletonLock(); } } } return(instance); }
public static SingletonLock getInstance() { if (_instance == null) { lock (syncRoot) { if (_instance == null) { _instance = new SingletonLock(); } } } return(_instance); }
public static SingletonLock GetInstance() { if (_instance == null) { lock (_lock) { if (_instance == null) { _instance = new SingletonLock(); } } } return(_instance); }
//https://metanit.com/sharp/patterns/2.3.php //https://refactoring.guru/ru/design-patterns/singleton/csharp/example#example-1 //https://professorweb.ru/my/it/blog/net/singleton_csharp.php //https://shwanoff.ru/singleton/amp/ static void Main(string[] args) { (new Thread(() => { Console.WriteLine(SingletonLock.getInstance().Date); })).Start(); (new Thread(() => { Console.WriteLine(SingletonLock.getInstance().Date); })).Start(); Console.WriteLine(SingletonLock.getInstance().Date); (new Thread(() => { Console.WriteLine(SingletonRO.getInstance().Date); })).Start(); (new Thread(() => { Console.WriteLine(SingletonRO.getInstance().Date); })).Start(); Console.WriteLine(SingletonRO.getInstance().Date); Console.WriteLine(SingletonNested.text); (new Thread(() => { Console.WriteLine(SingletonNested.getInstance().Date); })).Start(); (new Thread(() => { Console.WriteLine(SingletonNested.getInstance().Date); })).Start(); Console.WriteLine(SingletonNested.getInstance().Date); (new Thread(() => { Console.WriteLine(SingletonROLazy.getInstance().Date); })).Start(); (new Thread(() => { Console.WriteLine(SingletonROLazy.getInstance().Date); })).Start(); Console.WriteLine(SingletonROLazy.getInstance().Date); Console.ReadLine(); }
/// <summary> /// Tratar de crear dos instancias de la clase y verificar que se devuelve la misma instancia. /// </summary> private static void CrearDosInstanciasDeLaClaseSingletonLock() { //Primera Instancia del singleton SingletonLock singleton = SingletonLock.Instance; // Hacemos una pausa de tres segundos Thread.Sleep(3000); // Intentamos instanciar un segundo Singleton SingletonLock segundoSingleton = SingletonLock.Instance; Console.WriteLine("Singleton Lock \n"); // Comprobamos que ambos objetos son referencias a la misma // instancia, que es única Console.WriteLine(string.Format("Instancia {0} creada a las {1}", singleton.Nombre, singleton.HoraArranque.ToLongTimeString())); Console.WriteLine(string.Format("Instancia {0} creada a las {1}", segundoSingleton.Nombre, segundoSingleton.HoraArranque.ToLongTimeString())); Console.WriteLine("---------------"); Console.WriteLine("El singleton Lock se creó a las " + SingletonLock.Instance.HoraArranque.ToLongTimeString()); }