Advertisement
fcamuso

Singleton 2 - thread safety con lock

Jan 14th, 2021
464
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.04 KB | None | 0 0
  1. using System;
  2.  
  3. namespace SingletonEasy
  4. {
  5.   //static class MyClassStatic
  6.   //{
  7.   //  static readonly double dati;
  8.   //  public static double Dati { get { return dati; } }
  9.  
  10.   //  static MyClassStatic()
  11.   //  {
  12.   //    //altro codice di inizializzazione
  13.   //    dati = 3.14;
  14.   //  }
  15.   //}
  16.  
  17.   class MyClass
  18.   {
  19.     static private readonly object forLock = new object();
  20.  
  21.     static private MyClass instance = null;
  22.     static public MyClass Instance
  23.     {
  24.       get
  25.       {
  26.         if (instance == null)
  27.         {
  28.           lock (forLock)
  29.           {
  30.             if (instance == null) instance = new MyClass();
  31.           }
  32.         }
  33.  
  34.         return instance;
  35.  
  36.         //return instance ??= new MyClass(); //null-coalescing
  37.       }
  38.     }
  39.  
  40.     public void Metodo() { Console.WriteLine("metodo richiamato"); }
  41.  
  42.     private MyClass() { Console.WriteLine("Oggetto creato"); }
  43.   }
  44.  
  45.   class Program
  46.   {
  47.     static void Main(string[] args)
  48.     {
  49.       MyClass.Instance.Metodo();
  50.       MyClass.Instance.Metodo();
  51.     }
  52.   }
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement