Lazy.cs 3.2 KB

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