Skip to content

Commit 57fd56a

Browse files
Ensure that JsonSerializerOptions.CachingContext is a singleton. (#94527)
1 parent be238ac commit 57fd56a

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs

+8-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
using System.Runtime.ExceptionServices;
1010
using System.Text.Json.Serialization;
1111
using System.Text.Json.Serialization.Metadata;
12+
using System.Threading;
1213

1314
namespace System.Text.Json
1415
{
@@ -24,7 +25,13 @@ internal CachingContext CacheContext
2425
get
2526
{
2627
Debug.Assert(IsReadOnly);
27-
return _cachingContext ??= TrackedCachingContexts.GetOrCreate(this);
28+
return _cachingContext ?? GetOrCreate();
29+
30+
CachingContext GetOrCreate()
31+
{
32+
CachingContext ctx = TrackedCachingContexts.GetOrCreate(this);
33+
return Interlocked.CompareExchange(ref _cachingContext, ctx, null) ?? ctx;
34+
}
2835
}
2936
}
3037

0 commit comments

Comments
 (0)