Merge remote branch 'upstream/master'
[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 // 
7 // Copyright (c) 2009 Jérémie "Garuma" Laval
8 // 
9 // Permission is hereby granted, free of charge, to any person obtaining a copy
10 // of this software and associated documentation files (the "Software"), to deal
11 // in the Software without restriction, including without limitation the rights
12 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 // copies of the Software, and to permit persons to whom the Software is
14 // furnished to do so, subject to the following conditions:
15 // 
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
18 // 
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 // THE SOFTWARE.
26
27 #if NET_4_0
28 using System;
29 using System.Runtime.Serialization;
30 using System.Runtime.InteropServices;
31 using System.Security.Permissions;
32
33 namespace System.Threading
34 {
35         [HostProtection (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
36         [System.Diagnostics.DebuggerDisplay ("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}")]
37         [System.Diagnostics.DebuggerTypeProxy ("System.Threading.SystemThreading_ThreadLocalDebugView`1")]
38         public class ThreadLocal<T> : IDisposable
39         {
40                 readonly Func<T> valueFactory;
41                 LocalDataStoreSlot localStore;
42                 Exception cachedException;
43                 
44                 class DataSlotWrapper
45                 {
46                         public bool Creating;
47                         public bool Init;
48                         public Func<T> Getter;
49                 }
50                 
51                 public ThreadLocal () : this (LazyInitializer.GetDefaultValueFactory<T>)
52                 {
53                 }
54
55                 public ThreadLocal (Func<T> valueFactory)
56                 {
57                         if (valueFactory == null)
58                                 throw new ArgumentNullException ("valueFactory");
59                         
60                         localStore = Thread.AllocateDataSlot ();
61                         this.valueFactory = valueFactory;
62                 }
63                 
64                 public void Dispose ()
65                 {
66                         Dispose (true);
67                 }
68                 
69                 protected virtual void Dispose (bool disposing)
70                 {
71                         
72                 }
73                 
74                 public bool IsValueCreated {
75                         get {
76                                 ThrowIfNeeded ();
77                                 return IsInitializedThreadLocal ();
78                         }
79                 }
80                 
81                 public T Value {
82                         get {
83                                 ThrowIfNeeded ();
84                                 return GetValueThreadLocal ();
85                         }
86                         set {
87                                 ThrowIfNeeded ();
88
89                                 DataSlotWrapper w = GetWrapper ();
90                                 w.Init = true;
91                                 w.Getter = () => value;
92                         }
93                 }
94                 
95                 public override string ToString ()
96                 {
97                         return string.Format ("[ThreadLocal: IsValueCreated={0}, Value={1}]", IsValueCreated, Value);
98                 }
99                 
100                 T GetValueThreadLocal ()
101                 {
102                         DataSlotWrapper myWrapper = GetWrapper ();
103                         if (myWrapper.Creating)
104                                 throw new InvalidOperationException ("The initialization function attempted to reference Value recursively");
105
106                         return myWrapper.Getter ();
107                 }
108                 
109                 bool IsInitializedThreadLocal ()
110                 {
111                         DataSlotWrapper myWrapper = GetWrapper ();
112
113                         return myWrapper.Init;
114                 }
115
116                 DataSlotWrapper GetWrapper ()
117                 {
118                         DataSlotWrapper myWrapper = (DataSlotWrapper)Thread.GetData (localStore);
119                         if (myWrapper == null) {
120                                 myWrapper = DataSlotCreator ();
121                                 Thread.SetData (localStore, myWrapper);
122                         }
123
124                         return myWrapper;
125                 }
126
127                 void ThrowIfNeeded ()
128                 {
129                         if (cachedException != null)
130                                 throw cachedException;
131                 }
132
133                 DataSlotWrapper DataSlotCreator ()
134                 {
135                         DataSlotWrapper wrapper = new DataSlotWrapper ();
136                         Func<T> valSelector = valueFactory;
137         
138                         wrapper.Getter = delegate {
139                                 wrapper.Creating = true;
140                                 try {
141                                         T val = valSelector ();
142                                         wrapper.Creating = false;
143                                         wrapper.Init = true;
144                                         wrapper.Getter = () => val;
145                                         return val;
146                                 } catch (Exception e) {
147                                         cachedException = e;
148                                         throw e;
149                                 }
150                         };
151                         
152                         return wrapper;
153                 }
154         }
155 }
156 #endif