Lazy.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if NO_LAZY
  3. #pragma warning disable 0420
  4. //
  5. // Based on ndp\clr\src\BCL\System\Lazy.cs but with LazyThreadSafetyMode.ExecutionAndPublication mode behavior hardcoded.
  6. //
  7. using System.Diagnostics;
  8. using System.Threading;
  9. using System.Reactive;
  10. namespace System
  11. {
  12. internal class Lazy<T>
  13. {
  14. class Boxed
  15. {
  16. internal Boxed(T value)
  17. {
  18. m_value = value;
  19. }
  20. internal T m_value;
  21. }
  22. static Func<T> ALREADY_INVOKED_SENTINEL = delegate { return default(T); };
  23. private object m_boxed;
  24. private Func<T> m_valueFactory;
  25. private volatile object m_threadSafeObj;
  26. public Lazy(Func<T> valueFactory)
  27. {
  28. m_threadSafeObj = new object();
  29. m_valueFactory = valueFactory;
  30. }
  31. #if !NO_DEBUGGER_ATTRIBUTES
  32. [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  33. #endif
  34. public T Value
  35. {
  36. get
  37. {
  38. Boxed boxed = null;
  39. if (m_boxed != null)
  40. {
  41. boxed = m_boxed as Boxed;
  42. if (boxed != null)
  43. {
  44. return boxed.m_value;
  45. }
  46. var exc = m_boxed as Exception;
  47. exc.Throw();
  48. }
  49. return LazyInitValue();
  50. }
  51. }
  52. private T LazyInitValue()
  53. {
  54. Boxed boxed = null;
  55. object threadSafeObj = m_threadSafeObj;
  56. bool lockTaken = false;
  57. try
  58. {
  59. if (threadSafeObj != (object)ALREADY_INVOKED_SENTINEL)
  60. {
  61. Monitor.Enter(threadSafeObj);
  62. lockTaken = true;
  63. }
  64. if (m_boxed == null)
  65. {
  66. boxed = CreateValue();
  67. m_boxed = boxed;
  68. m_threadSafeObj = ALREADY_INVOKED_SENTINEL;
  69. }
  70. else
  71. {
  72. boxed = m_boxed as Boxed;
  73. if (boxed == null)
  74. {
  75. var exc = m_boxed as Exception;
  76. exc.Throw();
  77. }
  78. }
  79. }
  80. finally
  81. {
  82. if (lockTaken)
  83. Monitor.Exit(threadSafeObj);
  84. }
  85. return boxed.m_value;
  86. }
  87. private Boxed CreateValue()
  88. {
  89. Boxed boxed = null;
  90. try
  91. {
  92. if (m_valueFactory == ALREADY_INVOKED_SENTINEL)
  93. throw new InvalidOperationException();
  94. Func<T> factory = m_valueFactory;
  95. m_valueFactory = ALREADY_INVOKED_SENTINEL;
  96. boxed = new Boxed(factory());
  97. }
  98. catch (Exception ex)
  99. {
  100. m_boxed = ex;
  101. throw;
  102. }
  103. return boxed;
  104. }
  105. }
  106. }
  107. #pragma warning restore 0420
  108. #endif