static void Main(string[] args)
        {
            Singleton s1 = Singleton.Instance;
            Singleton s2 = Singleton.Instance;

            Console.WriteLine("s1: " + s1.GetHashCode() + ", s2: " + s2.GetHashCode());
            s1.doSomething();
            s2.doSomething();


            Console.WriteLine("\n\nTesting Singleton Pattern use multiple threading.");
            Task.Run(() =>
            {
                System.Threading.Thread.Sleep(5000);
                SingletonThreadSafe s12 = SingletonThreadSafe.Instance;
                Console.WriteLine($"first: {s12.GetHashCode()}");
                s12.doSomething();
            });
            Task.Run(() =>
            {
                System.Threading.Thread.Sleep(5000);
                SingletonThreadSafe s22 = SingletonThreadSafe.Instance;
                Console.WriteLine($"second: {s22.GetHashCode()}");
                s22.doSomething();
            });
            Console.ReadLine();
        }
Esempio n. 2
0
 public static SingletonThreadSafe GetInstance(string value)
 {
     if (_instance == null)
     {
         // Use a lock to prevent multiple threads from creating instances
         lock (_lock)
         {
             if (_instance == null)
             {
                 _instance       = new SingletonThreadSafe();
                 _instance.Value = value;
             }
         }
     }
     return(_instance);
 }
Esempio n. 3
0
        static void Main(string[] args)
        {
            //SingletonExample se = SingletonExample.Instance;
            //se.InstanceCheck();

            //SingletonExample se1 = SingletonExample.Instance;
            //se1.InstanceCheck();
            //se.InstanceCheck();

            SingletonThreadSafe stf = SingletonThreadSafe.Instance;

            stf.InstanceCheck();
            stf.InstanceCheck();

            SingletonThreadSafe stf1 = SingletonThreadSafe.Instance;

            stf1.InstanceCheck();
            stf.InstanceCheck();
        }
Esempio n. 4
0
        public static void TestThreadSafeSingleton(string value)
        {
            var singleton = SingletonThreadSafe.GetInstance(value);

            Console.WriteLine(singleton.Value);
        }