Skip to content

Commit b277911

Browse files
authored
replaced Dictionary with ConcurrentDictionary (#3101)
1 parent c2844aa commit b277911

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

src/Stripe.net/Infrastructure/JsonConverters/SerializablePropertyCache.cs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
namespace Stripe.Infrastructure
33
{
44
using System;
5+
using System.Collections.Concurrent;
56
using System.Collections.Generic;
67
using System.Reflection;
78
using System.Text.Json;
@@ -13,17 +14,17 @@ namespace Stripe.Infrastructure
1314
/// </summary>
1415
internal class SerializablePropertyCache
1516
{
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>>();
1819

1920
internal static List<SerializablePropertyInfo> GetPropertiesForType(Type type)
2021
{
21-
if (!propertyCache.TryGetValue(type, out var propsToSerialize))
22+
return propertyCache.GetOrAdd(type, (key) =>
2223
{
2324
// Gets the all properties including nonpublic properties
2425
var rawProps = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
2526

26-
propsToSerialize = new List<SerializablePropertyInfo>();
27+
var propsToSerialize = new List<SerializablePropertyInfo>();
2728
foreach (var prop in rawProps)
2829
{
2930
var propertyNameAttribute = prop.GetCustomAttribute(typeof(JsonPropertyNameAttribute), false) as JsonPropertyNameAttribute;
@@ -55,10 +56,8 @@ internal static List<SerializablePropertyInfo> GetPropertiesForType(Type type)
5556
});
5657
}
5758

58-
propertyCache[type] = propsToSerialize;
59-
}
60-
61-
return propsToSerialize;
59+
return propsToSerialize;
60+
});
6261
}
6362

6463
// Create the various methods stored in SerializablePropertyInfo
@@ -169,11 +168,10 @@ private static Action<object, object> CreateSetDelegate<T, TValue>(MethodInfo m)
169168
private static JsonConverter<object> GetConverterForType<T, TV>(Type ct)
170169
where T : JsonConverter<TV>
171170
{
172-
if (!converterCache.TryGetValue(ct, out var conv))
171+
var conv = converterCache.GetOrAdd(ct, (key) =>
173172
{
174-
conv = (JsonConverter)Activator.CreateInstance(ct);
175-
converterCache[ct] = conv;
176-
}
173+
return (JsonConverter)Activator.CreateInstance(ct);
174+
});
177175

178176
return new JsonConverterAdapter<T, TV>((T)conv);
179177
}

0 commit comments

Comments
 (0)