Merge pull request #900 from Blewzman/FixAggregateExceptionGetBaseException
[mono.git] / mcs / class / corlib / System.Threading / ThreadLocal.cs
1 // 
2 // ThreadLocal.cs
3 //  
4 // Author:
5 //       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
6 //       Rewritten by Paolo Molaro (lupus@ximian.com)
7 // 
8 // Copyright (c) 2009 Jérémie "Garuma" Laval
9 // 
10 // Permission is hereby granted, free of charge, to any person obtaining a copy
11 // of this software and associated documentation files (the "Software"), to deal
12 // in the Software without restriction, including without limitation the rights
13 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 // copies of the Software, and to permit persons to whom the Software is
15 // furnished to do so, subject to the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be included in
18 // all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 // THE SOFTWARE.
27
28 #if NET_4_0
29 using System;
30 using System.Collections.Generic;
31 using System.Runtime.Serialization;
32 using System.Runtime.InteropServices;
33 using System.Security.Permissions;
34
35 namespace System.Threading
36 {
37         [System.Diagnostics.DebuggerDisplay ("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}")]
38         public class ThreadLocal<T> : IDisposable
39         {
40                 struct TlsDatum {
41                         internal sbyte state; /* 0 uninitialized, < 0 initializing, > 0 inited */
42                         internal Exception cachedException; /* this is per-thread */
43                         internal T data;
44                 }
45
46                 Func<T> valueFactory;
47                 /* The tlsdata field is handled magically by the JIT
48                  * It must be a struct and it is always accessed by ldflda: the JIT, instead of
49                  * computing the address inside the instance, will return the address of the variable
50                  * for the current thread (based on tls_offset). This magic wouldn't be needed if C#
51                  * let us declare an icall with a TlsDatum& return type...
52                  * For this same reason, we must check tls_offset for != 0 to make sure it's valid before accessing tlsdata
53                  * The address of the tls var is cached per method at the first IL ldflda instruction, so care must be taken
54                  * not to cause it to be conditionally executed.
55                  */
56                 uint tls_offset;
57                 TlsDatum tlsdata;
58                 
59                 public ThreadLocal ()
60                 {
61                         tls_offset = Thread.AllocTlsData (typeof (TlsDatum));
62                 }
63
64                 public ThreadLocal (Func<T> valueFactory) : this ()
65                 {
66                         if (valueFactory == null)
67                                 throw new ArgumentNullException ("valueFactory");
68                         this.valueFactory = valueFactory;
69                 }
70
71 #if NET_4_5
72                 public ThreadLocal (bool trackAllValues) : this () {
73                         if (trackAllValues)
74                                 throw new NotImplementedException ();
75                 }
76
77                 public ThreadLocal (Func<T> valueFactory, bool trackAllValues) : this (valueFactory) {
78                         if (trackAllValues)
79                                 throw new NotImplementedException ();
80                 }
81 #endif
82
83                 public void Dispose ()
84                 {
85                         Dispose (true);
86                 }
87                 
88                 protected virtual void Dispose (bool disposing)
89                 {
90                         if (tls_offset != 0) {
91                                 uint o = tls_offset;
92                                 tls_offset = 0;
93                                 if (disposing)
94                                         valueFactory = null;
95                                 Thread.DestroyTlsData (o);
96                                 GC.SuppressFinalize (this);
97                         }
98                 }
99
100                 ~ThreadLocal ()
101                 {
102                         Dispose (false);
103                 }
104                 
105                 public bool IsValueCreated {
106                         get {
107                                 if (tls_offset == 0)
108                                         throw new ObjectDisposedException ("ThreadLocal object");
109                                 /* ALERT! magic tlsdata JIT access redirects to TLS value instead of instance field */
110                                 return tlsdata.state > 0;
111                         }
112                 }
113
114                 T GetSlowPath () {
115                         /* ALERT! magic tlsdata JIT access redirects to TLS value instead of instance field */
116                         if (tlsdata.cachedException != null)
117                                 throw tlsdata.cachedException;
118                         if (tlsdata.state < 0)
119                                 throw new InvalidOperationException ("The initialization function attempted to reference Value recursively");
120                         tlsdata.state = -1;
121                         if (valueFactory != null) {
122                                 try {
123                                         tlsdata.data = valueFactory ();
124                                 } catch (Exception ex) {
125                                         tlsdata.cachedException = ex;
126                                         throw ex;
127                                 }
128                         } else {
129                                 tlsdata.data = default (T);
130                         }
131                         tlsdata.state = 1;
132                         return tlsdata.data;
133                 }
134
135                 [System.Diagnostics.DebuggerBrowsableAttribute (System.Diagnostics.DebuggerBrowsableState.Never)]
136                 public T Value {
137                         get {
138                                 if (tls_offset == 0)
139                                         throw new ObjectDisposedException ("ThreadLocal object");
140                                 /* ALERT! magic tlsdata JIT access redirects to TLS value instead of instance field */
141                                 if (tlsdata.state > 0)
142                                         return tlsdata.data;
143                                 return GetSlowPath ();
144                         }
145                         set {
146                                 if (tls_offset == 0)
147                                         throw new ObjectDisposedException ("ThreadLocal object");
148                                 /* ALERT! magic tlsdata JIT access redirects to TLS value instead of instance field */
149                                 tlsdata.state = 1;
150                                 tlsdata.data = value;
151                         }
152                 }
153
154 #if NET_4_5
155                 public IList<T> Values {
156                         get {
157                                 if (tls_offset == 0)
158                                         throw new ObjectDisposedException ("ThreadLocal object");
159                                 throw new NotImplementedException ();
160                         }
161                 }
162 #endif
163
164                 public override string ToString ()
165                 {
166                         return Value.ToString ();
167                 }
168                 
169         }
170 }
171 #endif