Advertisement
yakovmonarh

Singleton потокобезопасная реализация без lock

Aug 20th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.67 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3. using System.Linq;
  4.  
  5. class Program
  6. {
  7.    static void Main(string[] args)
  8.    {
  9.         (new Thread(()=>
  10.         {
  11.              var sing = Singleton.GetInstance();
  12.              Console.WriteLine(sing.Date);
  13.         })).Start();
  14.        
  15.         var sing2 = Singleton.GetInstance();
  16.         Console.WriteLine(sing2.Date);
  17.        
  18.         Console.ReadLine();
  19.    }
  20. }
  21.  
  22. class Singleton
  23. {
  24.     private static readonly Singleton instance = new Singleton();
  25.    
  26.     public string Date{get; private set;}
  27.    
  28.     private Singleton()
  29.     {
  30.         this.Date = DateTime.Now.TimeOfDay.ToString();
  31.     }
  32.    
  33.     public static Singleton GetInstance()
  34.     {
  35.         return instance;
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement