Skip to content

Commit

Permalink
Merge pull request #134 from omer-koren/fix/using-concurrent-dictionary
Browse files Browse the repository at this point in the history
fix: use double checking lock for type resolution
  • Loading branch information
soxtoby authored Dec 21, 2022
2 parents 4acd84b + 4b603e1 commit f667b53
Showing 1 changed file with 18 additions and 9 deletions.
27 changes: 18 additions & 9 deletions SlackNet/Serialization/SlackTypeResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,30 @@ public interface ISlackTypeResolver
class SlackTypeResolver : ISlackTypeResolver
{
private readonly Assembly[] _assemblies;
private readonly Dictionary<Type, Dictionary<string, Type>> _typeLookups = new();

private Dictionary<Type, Dictionary<string, Type>> _typeLookups = new();
private object _lock = new object();
public SlackTypeResolver(params Assembly[] assemblies) => _assemblies = assemblies;

public Type FindType(Type baseType, string slackType)
{
lock (_typeLookups)
Dictionary<string, Type> typeLookup;
if (!_typeLookups.TryGetValue(baseType, out typeLookup))
{
if (!_typeLookups.TryGetValue(baseType, out var lookup))
lookup = _typeLookups[baseType] = CreateLookup(baseType);

return lookup.TryGetValue(slackType, out var type)
? type
: baseType;
lock (_lock)
{
if (!_typeLookups.TryGetValue(baseType, out typeLookup))
{
var copy = _typeLookups.ToDictionary(x => x.Key, x => x.Value);
typeLookup = copy[baseType] = CreateLookup(baseType);
_typeLookups = copy;
}
}
}

return typeLookup.TryGetValue(slackType, out var type)
? type
: baseType;

}

private Dictionary<string, Type> CreateLookup(Type baseType)
Expand Down

0 comments on commit f667b53

Please sign in to comment.