Skip to content

Commit

Permalink
Made the typeconvertercache a concurrent dictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
EdwardCooke committed Sep 1, 2024
1 parent fc77398 commit 5737a3c
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions YamlDotNet/Serialization/Utilities/TypeConverterCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
// SOFTWARE.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
Expand All @@ -32,7 +33,7 @@ namespace YamlDotNet.Serialization.Utilities
internal sealed class TypeConverterCache
{
private readonly IYamlTypeConverter[] typeConverters;
private readonly Dictionary<Type, (bool HasMatch, IYamlTypeConverter TypeConverter)> cache = new();
private readonly ConcurrentDictionary<Type, (bool HasMatch, IYamlTypeConverter? TypeConverter)> cache = new();

public TypeConverterCache(IEnumerable<IYamlTypeConverter>? typeConverters) : this(typeConverters?.ToArray() ?? Array.Empty<IYamlTypeConverter>())
{
Expand All @@ -51,18 +52,15 @@ public TypeConverterCache(IYamlTypeConverter[] typeConverters)
/// <returns><see langword="true"/> if a type converter was found; <see langword="false"/> otherwise.</returns>
public bool TryGetConverterForType(Type type, [NotNullWhen(true)] out IYamlTypeConverter? typeConverter)
{
if (cache.TryGetValue(type, out var result))
var result = cache.GetOrAdd(type, (t) =>
{
typeConverter = result.TypeConverter;
return result.HasMatch;
}

typeConverter = LookupTypeConverter(type);

var found = typeConverter is not null;
cache[type] = (found, typeConverter!);
var converter = LookupTypeConverter(type);
var found = converter != null;
return (found, converter);
});

return found;
typeConverter = result.TypeConverter;
return result.HasMatch;
}

/// <summary>
Expand Down

0 comments on commit 5737a3c

Please sign in to comment.