From 7654bf2c63d22dfdf197d54c1f4b7017aa556726 Mon Sep 17 00:00:00 2001 From: Krzysztof Wicher Date: Thu, 28 Apr 2022 16:27:30 +0200 Subject: [PATCH] Lock EnsureConfigured to prevent initialization issues in JsonTypeInfo (#68605) * Lock EnsureConfigured to prevent initialization issues in JsonTypeInfo * do not use this for lock, ensure we call Configure from lock --- .../Text/Json/Serialization/Metadata/JsonTypeInfo.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs index 5ee0e9109526b..4285bba6669fb 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs @@ -195,19 +195,27 @@ internal JsonTypeInfo(Type type, JsonConverter converter, JsonSerializerOptions } private bool _isConfigured; + private object _configureLock = new object(); internal void EnsureConfigured() { if (_isConfigured) return; - Configure(); + lock (_configureLock) + { + if (_isConfigured) + return; + + Configure(); - _isConfigured = true; + _isConfigured = true; + } } internal virtual void Configure() { + Debug.Assert(Monitor.IsEntered(_configureLock), "Configure called directly, use EnsureConfigured which locks this method"); JsonConverter converter = PropertyInfoForTypeInfo.ConverterBase; Debug.Assert(PropertyInfoForTypeInfo.ConverterStrategy == PropertyInfoForTypeInfo.ConverterBase.ConverterStrategy, $"ConverterStrategy from PropertyInfoForTypeInfo.ConverterStrategy ({PropertyInfoForTypeInfo.ConverterStrategy}) does not match converter's ({PropertyInfoForTypeInfo.ConverterBase.ConverterStrategy})");