diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/LazyInitializer.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/LazyInitializer.cs index 7b570f05a9557d..b2fddf32f8cfba 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/LazyInitializer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/LazyInitializer.cs @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; namespace System.Threading { @@ -111,10 +112,18 @@ public static T EnsureInitialized([NotNull] ref T? target, Func valueFacto /// The initialized variable private static T EnsureInitializedCore([NotNull] ref T? target, Func valueFactory) where T : class { - T value = valueFactory() ?? throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation); + T? value = valueFactory(); + if (value is null) + { + Throw(); + } + Interlocked.CompareExchange(ref target, value, null!); Debug.Assert(target != null); return target; + + [DoesNotReturn] + static void Throw() => throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation); } ///