Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Made the typeconvertercache a concurrent dictionary #962

Merged
merged 1 commit into from
Sep 1, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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