ThreadLocal.cs 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. //
  2. // ThreadLocal.cs
  3. //
  4. // Author:
  5. // Jérémie "Garuma" Laval <[email protected]>
  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. #if NET_4_0
  27. using System;
  28. using System.Runtime.Serialization;
  29. using System.Runtime.InteropServices;
  30. using System.Security.Permissions;
  31. namespace System.Threading
  32. {
  33. [HostProtection (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
  34. [System.Diagnostics.DebuggerDisplay ("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}")]
  35. [System.Diagnostics.DebuggerTypeProxy ("System.Threading.SystemThreading_ThreadLocalDebugView`1")]
  36. public class ThreadLocal<T> : IDisposable
  37. {
  38. readonly Func<T> valueFactory;
  39. LocalDataStoreSlot localStore;
  40. Exception cachedException;
  41. class DataSlotWrapper
  42. {
  43. public bool Creating;
  44. public bool Init;
  45. public Func<T> Getter;
  46. }
  47. public ThreadLocal () : this (LazyInitializer.GetDefaultValueFactory<T>)
  48. {
  49. }
  50. public ThreadLocal (Func<T> valueFactory)
  51. {
  52. if (valueFactory == null)
  53. throw new ArgumentNullException ("valueFactory");
  54. localStore = Thread.AllocateDataSlot ();
  55. this.valueFactory = valueFactory;
  56. }
  57. public void Dispose ()
  58. {
  59. Dispose (true);
  60. }
  61. protected virtual void Dispose (bool disposing)
  62. {
  63. }
  64. public bool IsValueCreated {
  65. get {
  66. ThrowIfNeeded ();
  67. return IsInitializedThreadLocal ();
  68. }
  69. }
  70. public T Value {
  71. get {
  72. ThrowIfNeeded ();
  73. return GetValueThreadLocal ();
  74. }
  75. set {
  76. ThrowIfNeeded ();
  77. DataSlotWrapper w = GetWrapper ();
  78. w.Init = true;
  79. w.Getter = () => value;
  80. }
  81. }
  82. public override string ToString ()
  83. {
  84. return string.Format ("[ThreadLocal: IsValueCreated={0}, Value={1}]", IsValueCreated, Value);
  85. }
  86. T GetValueThreadLocal ()
  87. {
  88. DataSlotWrapper myWrapper = GetWrapper ();
  89. if (myWrapper.Creating)
  90. throw new InvalidOperationException ("The initialization function attempted to reference Value recursively");
  91. return myWrapper.Getter ();
  92. }
  93. bool IsInitializedThreadLocal ()
  94. {
  95. DataSlotWrapper myWrapper = GetWrapper ();
  96. return myWrapper.Init;
  97. }
  98. DataSlotWrapper GetWrapper ()
  99. {
  100. DataSlotWrapper myWrapper = (DataSlotWrapper)Thread.GetData (localStore);
  101. if (myWrapper == null) {
  102. myWrapper = DataSlotCreator ();
  103. Thread.SetData (localStore, myWrapper);
  104. }
  105. return myWrapper;
  106. }
  107. void ThrowIfNeeded ()
  108. {
  109. if (cachedException != null)
  110. throw cachedException;
  111. }
  112. DataSlotWrapper DataSlotCreator ()
  113. {
  114. DataSlotWrapper wrapper = new DataSlotWrapper ();
  115. Func<T> valSelector = valueFactory;
  116. wrapper.Getter = delegate {
  117. wrapper.Creating = true;
  118. try {
  119. T val = valSelector ();
  120. wrapper.Creating = false;
  121. wrapper.Init = true;
  122. wrapper.Getter = () => val;
  123. return val;
  124. } catch (Exception e) {
  125. cachedException = e;
  126. throw e;
  127. }
  128. };
  129. return wrapper;
  130. }
  131. }
  132. }
  133. #endif