Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Core/Reactive/Internal/Lazy.cs

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