2
2
namespace Stripe . Infrastructure
3
3
{
4
4
using System ;
5
+ using System . Collections . Concurrent ;
5
6
using System . Collections . Generic ;
6
7
using System . Reflection ;
7
8
using System . Text . Json ;
@@ -13,17 +14,17 @@ namespace Stripe.Infrastructure
13
14
/// </summary>
14
15
internal class SerializablePropertyCache
15
16
{
16
- private static Dictionary < Type , JsonConverter > converterCache = new Dictionary < Type , JsonConverter > ( ) ;
17
- private static Dictionary < Type , List < SerializablePropertyInfo > > propertyCache = new Dictionary < Type , List < SerializablePropertyInfo > > ( ) ;
17
+ private static ConcurrentDictionary < Type , JsonConverter > converterCache = new ConcurrentDictionary < Type , JsonConverter > ( ) ;
18
+ private static ConcurrentDictionary < Type , List < SerializablePropertyInfo > > propertyCache = new ConcurrentDictionary < Type , List < SerializablePropertyInfo > > ( ) ;
18
19
19
20
internal static List < SerializablePropertyInfo > GetPropertiesForType ( Type type )
20
21
{
21
- if ( ! propertyCache . TryGetValue ( type , out var propsToSerialize ) )
22
+ return propertyCache . GetOrAdd ( type , ( key ) =>
22
23
{
23
24
// Gets the all properties including nonpublic properties
24
25
var rawProps = type . GetProperties ( BindingFlags . Public | BindingFlags . NonPublic | BindingFlags . Instance ) ;
25
26
26
- propsToSerialize = new List < SerializablePropertyInfo > ( ) ;
27
+ var propsToSerialize = new List < SerializablePropertyInfo > ( ) ;
27
28
foreach ( var prop in rawProps )
28
29
{
29
30
var propertyNameAttribute = prop . GetCustomAttribute ( typeof ( JsonPropertyNameAttribute ) , false ) as JsonPropertyNameAttribute ;
@@ -55,10 +56,8 @@ internal static List<SerializablePropertyInfo> GetPropertiesForType(Type type)
55
56
} ) ;
56
57
}
57
58
58
- propertyCache [ type ] = propsToSerialize ;
59
- }
60
-
61
- return propsToSerialize ;
59
+ return propsToSerialize ;
60
+ } ) ;
62
61
}
63
62
64
63
// Create the various methods stored in SerializablePropertyInfo
@@ -169,11 +168,10 @@ private static Action<object, object> CreateSetDelegate<T, TValue>(MethodInfo m)
169
168
private static JsonConverter < object > GetConverterForType < T , TV > ( Type ct )
170
169
where T : JsonConverter < TV >
171
170
{
172
- if ( ! converterCache . TryGetValue ( ct , out var conv ) )
171
+ var conv = converterCache . GetOrAdd ( ct , ( key ) =>
173
172
{
174
- conv = ( JsonConverter ) Activator . CreateInstance ( ct ) ;
175
- converterCache [ ct ] = conv ;
176
- }
173
+ return ( JsonConverter ) Activator . CreateInstance ( ct ) ;
174
+ } ) ;
177
175
178
176
return new JsonConverterAdapter < T , TV > ( ( T ) conv ) ;
179
177
}
0 commit comments