Advertisement
Guest User

Untitled

a guest
Feb 28th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3.  
  4. namespace ConsoleApplication2
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. var sw = Stopwatch.StartNew();
  11.  
  12. for (int i = 0; i < 10000000; i++)
  13. {
  14. var instance = LazySingleton.Instance;
  15. //var instance = DoubleCheckLockSingleton.Instance;
  16. }
  17. Console.WriteLine(sw.ElapsedMilliseconds);
  18. }
  19. }
  20.  
  21. public class LazySingleton
  22. {
  23. private static readonly Lazy<LazySingleton> _instance
  24. = new Lazy<LazySingleton>(() => new LazySingleton(), isThreadSafe: true);
  25.  
  26. private LazySingleton() {}
  27.  
  28. public static LazySingleton Instance => _instance.Value;
  29. }
  30.  
  31. public class DoubleCheckLockSingleton
  32. {
  33. private static readonly object SyncObj = new object();
  34. private static volatile DoubleCheckLockSingleton _instance = null;
  35.  
  36. private DoubleCheckLockSingleton(){ }
  37.  
  38. public static DoubleCheckLockSingleton Instance
  39. {
  40. get
  41. {
  42. if (_instance == null)
  43. {
  44. lock (SyncObj)
  45. {
  46. if (_instance == null)
  47. {
  48. _instance = new DoubleCheckLockSingleton();
  49. }
  50. }
  51. }
  52. return _instance;
  53. }
  54. }
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement