LazyInitializer.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
  5. //
  6. // a set of lightweight static helpers for lazy initialization.
  7. //
  8. // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  9. using System.Diagnostics;
  10. using System.Diagnostics.CodeAnalysis;
  11. namespace System.Threading
  12. {
  13. /// <summary>
  14. /// Provides lazy initialization routines.
  15. /// </summary>
  16. /// <remarks>
  17. /// These routines avoid needing to allocate a dedicated, lazy-initialization instance, instead using
  18. /// references to ensure targets have been initialized as they are accessed.
  19. /// </remarks>
  20. public static class LazyInitializer
  21. {
  22. /// <summary>
  23. /// Initializes a target reference type with the type's default constructor if the target has not
  24. /// already been initialized.
  25. /// </summary>
  26. /// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
  27. /// <param name="target">A reference of type <typeparamref name="T"/> to initialize if it has not
  28. /// already been initialized.</param>
  29. /// <returns>The initialized reference of type <typeparamref name="T"/>.</returns>
  30. /// <exception cref="T:System.MissingMemberException">Type <typeparamref name="T"/> does not have a default
  31. /// constructor.</exception>
  32. /// <exception cref="T:System.MemberAccessException">
  33. /// Permissions to access the constructor of type <typeparamref name="T"/> were missing.
  34. /// </exception>
  35. /// <remarks>
  36. /// <para>
  37. /// This method may only be used on reference types. To ensure initialization of value
  38. /// types, see other overloads of EnsureInitialized.
  39. /// </para>
  40. /// <para>
  41. /// This method may be used concurrently by multiple threads to initialize <paramref name="target"/>.
  42. /// In the event that multiple threads access this method concurrently, multiple instances of <typeparamref name="T"/>
  43. /// may be created, but only one will be stored into <paramref name="target"/>. In such an occurrence, this method will not dispose of the
  44. /// objects that were not stored. If such objects must be disposed, it is up to the caller to determine
  45. /// if an object was not used and to then dispose of the object appropriately.
  46. /// </para>
  47. /// </remarks>
  48. public static T EnsureInitialized<T>([NotNull] ref T? target) where T : class =>
  49. Volatile.Read(ref target) ?? EnsureInitializedCore(ref target);
  50. /// <summary>
  51. /// Initializes a target reference type with the type's default constructor (slow path)
  52. /// </summary>
  53. /// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
  54. /// <param name="target">The variable that need to be initialized</param>
  55. /// <returns>The initialized variable</returns>
  56. private static T EnsureInitializedCore<T>([NotNull] ref T? target) where T : class
  57. {
  58. try
  59. {
  60. Interlocked.CompareExchange(ref target, Activator.CreateInstance<T>(), null!);
  61. }
  62. catch (MissingMethodException)
  63. {
  64. throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT);
  65. }
  66. Debug.Assert(target != null);
  67. return target;
  68. }
  69. /// <summary>
  70. /// Initializes a target reference type using the specified function if it has not already been
  71. /// initialized.
  72. /// </summary>
  73. /// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
  74. /// <param name="target">The reference of type <typeparamref name="T"/> to initialize if it has not
  75. /// already been initialized.</param>
  76. /// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the
  77. /// reference.</param>
  78. /// <returns>The initialized reference of type <typeparamref name="T"/>.</returns>
  79. /// <exception cref="T:System.MissingMemberException">Type <typeparamref name="T"/> does not have a
  80. /// default constructor.</exception>
  81. /// <exception cref="T:System.InvalidOperationException"><paramref name="valueFactory"/> returned
  82. /// null.</exception>
  83. /// <remarks>
  84. /// <para>
  85. /// This method may only be used on reference types, and <paramref name="valueFactory"/> may
  86. /// not return a null reference (Nothing in Visual Basic). To ensure initialization of value types or
  87. /// to allow null reference types, see other overloads of EnsureInitialized.
  88. /// </para>
  89. /// <para>
  90. /// This method may be used concurrently by multiple threads to initialize <paramref name="target"/>.
  91. /// In the event that multiple threads access this method concurrently, multiple instances of <typeparamref name="T"/>
  92. /// may be created, but only one will be stored into <paramref name="target"/>. In such an occurrence, this method will not dispose of the
  93. /// objects that were not stored. If such objects must be disposed, it is up to the caller to determine
  94. /// if an object was not used and to then dispose of the object appropriately.
  95. /// </para>
  96. /// </remarks>
  97. public static T EnsureInitialized<T>([NotNull] ref T? target, Func<T> valueFactory) where T : class =>
  98. Volatile.Read(ref target) ?? EnsureInitializedCore(ref target, valueFactory);
  99. /// <summary>
  100. /// Initialize the target using the given delegate (slow path).
  101. /// </summary>
  102. /// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
  103. /// <param name="target">The variable that need to be initialized</param>
  104. /// <param name="valueFactory">The delegate that will be executed to initialize the target</param>
  105. /// <returns>The initialized variable</returns>
  106. private static T EnsureInitializedCore<T>([NotNull] ref T? target, Func<T> valueFactory) where T : class
  107. {
  108. T value = valueFactory();
  109. if (value == null)
  110. {
  111. throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation);
  112. }
  113. Interlocked.CompareExchange(ref target, value, null!);
  114. Debug.Assert(target != null);
  115. return target;
  116. }
  117. /// <summary>
  118. /// Initializes a target reference or value type with its default constructor if it has not already
  119. /// been initialized.
  120. /// </summary>
  121. /// <typeparam name="T">The type of the reference to be initialized.</typeparam>
  122. /// <param name="target">A reference or value of type <typeparamref name="T"/> to initialize if it
  123. /// has not already been initialized.</param>
  124. /// <param name="initialized">A reference to a boolean that determines whether the target has already
  125. /// been initialized.</param>
  126. /// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
  127. /// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
  128. /// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
  129. public static T EnsureInitialized<T>([AllowNull] ref T target, ref bool initialized, [NotNull] ref object? syncLock)
  130. {
  131. // Fast path.
  132. if (Volatile.Read(ref initialized))
  133. {
  134. return target;
  135. }
  136. return EnsureInitializedCore(ref target, ref initialized, ref syncLock);
  137. }
  138. /// <summary>
  139. /// Ensure the target is initialized and return the value (slow path). This overload permits nulls
  140. /// and also works for value type targets. Uses the type's default constructor to create the value.
  141. /// </summary>
  142. /// <typeparam name="T">The type of target.</typeparam>
  143. /// <param name="target">A reference to the target to be initialized.</param>
  144. /// <param name="initialized">A reference to a location tracking whether the target has been initialized.</param>
  145. /// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
  146. /// a new object will be instantiated.
  147. /// </param>
  148. /// <returns>The initialized object.</returns>
  149. private static T EnsureInitializedCore<T>([AllowNull] ref T target, ref bool initialized, [NotNull] ref object? syncLock)
  150. {
  151. // Lazily initialize the lock if necessary and then double check if initialization is still required.
  152. lock (EnsureLockInitialized(ref syncLock))
  153. {
  154. if (!Volatile.Read(ref initialized))
  155. {
  156. try
  157. {
  158. target = Activator.CreateInstance<T>();
  159. }
  160. catch (MissingMethodException)
  161. {
  162. throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT);
  163. }
  164. Volatile.Write(ref initialized, true);
  165. }
  166. }
  167. return target;
  168. }
  169. /// <summary>
  170. /// Initializes a target reference or value type with a specified function if it has not already been
  171. /// initialized.
  172. /// </summary>
  173. /// <typeparam name="T">The type of the reference to be initialized.</typeparam>
  174. /// <param name="target">A reference or value of type <typeparamref name="T"/> to initialize if it
  175. /// has not already been initialized.</param>
  176. /// <param name="initialized">A reference to a boolean that determines whether the target has already
  177. /// been initialized.</param>
  178. /// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
  179. /// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
  180. /// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the
  181. /// reference or value.</param>
  182. /// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
  183. public static T EnsureInitialized<T>([AllowNull] ref T target, ref bool initialized, [NotNull] ref object? syncLock, Func<T> valueFactory)
  184. {
  185. // Fast path.
  186. if (Volatile.Read(ref initialized))
  187. {
  188. return target;
  189. }
  190. return EnsureInitializedCore(ref target, ref initialized, ref syncLock, valueFactory);
  191. }
  192. /// <summary>
  193. /// Ensure the target is initialized and return the value (slow path). This overload permits nulls
  194. /// and also works for value type targets. Uses the supplied function to create the value.
  195. /// </summary>
  196. /// <typeparam name="T">The type of target.</typeparam>
  197. /// <param name="target">A reference to the target to be initialized.</param>
  198. /// <param name="initialized">A reference to a location tracking whether the target has been initialized.</param>
  199. /// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
  200. /// a new object will be instantiated.</param>
  201. /// <param name="valueFactory">
  202. /// The <see cref="T:System.Func{T}"/> to invoke in order to produce the lazily-initialized value.
  203. /// </param>
  204. /// <returns>The initialized object.</returns>
  205. private static T EnsureInitializedCore<T>([AllowNull] ref T target, ref bool initialized, [NotNull] ref object? syncLock, Func<T> valueFactory)
  206. {
  207. // Lazily initialize the lock if necessary and then double check if initialization is still required.
  208. lock (EnsureLockInitialized(ref syncLock))
  209. {
  210. if (!Volatile.Read(ref initialized))
  211. {
  212. target = valueFactory();
  213. Volatile.Write(ref initialized, true);
  214. }
  215. }
  216. return target;
  217. }
  218. /// <summary>
  219. /// Initializes a target reference type with a specified function if it has not already been initialized.
  220. /// </summary>
  221. /// <typeparam name="T">The type of the reference to be initialized. Has to be reference type.</typeparam>
  222. /// <param name="target">A reference of type <typeparamref name="T"/> to initialize if it has not already been initialized.</param>
  223. /// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
  224. /// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
  225. /// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the reference.</param>
  226. /// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
  227. public static T EnsureInitialized<T>([NotNull] ref T? target, [NotNull] ref object? syncLock, Func<T> valueFactory) where T : class =>
  228. Volatile.Read(ref target) ?? EnsureInitializedCore(ref target, ref syncLock, valueFactory);
  229. /// <summary>
  230. /// Ensure the target is initialized and return the value (slow path). This overload works only for reference type targets.
  231. /// Uses the supplied function to create the value.
  232. /// </summary>
  233. /// <typeparam name="T">The type of target. Has to be reference type.</typeparam>
  234. /// <param name="target">A reference to the target to be initialized.</param>
  235. /// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
  236. /// a new object will be instantiated.</param>
  237. /// <param name="valueFactory">
  238. /// The <see cref="T:System.Func{T}"/> to invoke in order to produce the lazily-initialized value.
  239. /// </param>
  240. /// <returns>The initialized object.</returns>
  241. private static T EnsureInitializedCore<T>([NotNull] ref T? target, [NotNull] ref object? syncLock, Func<T> valueFactory) where T : class
  242. {
  243. // Lazily initialize the lock if necessary and then double check if initialization is still required.
  244. lock (EnsureLockInitialized(ref syncLock))
  245. {
  246. if (Volatile.Read(ref target) == null)
  247. {
  248. Volatile.Write(ref target, valueFactory());
  249. if (target == null)
  250. {
  251. throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation);
  252. }
  253. }
  254. }
  255. return target!; // TODO-NULLABLE: Compiler can't infer target's non-nullness (https://github.com/dotnet/roslyn/issues/37300)
  256. }
  257. /// <summary>
  258. /// Ensure the lock object is initialized.
  259. /// </summary>
  260. /// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
  261. /// a new object will be instantiated.</param>
  262. /// <returns>Initialized lock object.</returns>
  263. private static object EnsureLockInitialized([NotNull] ref object? syncLock) =>
  264. syncLock ??
  265. Interlocked.CompareExchange(ref syncLock, new object(), null) ??
  266. syncLock;
  267. }
  268. }