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