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

Use ConcurrentDictionary instead of lock #363

Merged
merged 2 commits into from
Jun 16, 2021
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
18 changes: 3 additions & 15 deletions Source/Serilog.Exceptions/Reflection/ReflectionInfoExtractor.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
namespace Serilog.Exceptions.Reflection
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
Expand All @@ -12,8 +13,7 @@ namespace Serilog.Exceptions.Reflection
/// </summary>
internal class ReflectionInfoExtractor
{
private readonly object lockObj = new();
private readonly Dictionary<Type, ReflectionInfo> reflectionInfoCache = new();
private readonly ConcurrentDictionary<Type, ReflectionInfo> reflectionInfoCache = new();
private readonly IList<PropertyInfo> baseExceptionPropertiesForDestructuring;

/// <summary>
Expand All @@ -27,19 +27,7 @@ internal class ReflectionInfoExtractor
/// </summary>
/// <param name="valueType">The type for which properties are to be analyzed.</param>
/// <returns>The reflection info for relevant properties of <paramref name="valueType"/>.</returns>
public ReflectionInfo GetOrCreateReflectionInfo(Type valueType)
{
lock (this.lockObj)
{
if (!this.reflectionInfoCache.TryGetValue(valueType, out var reflectionInfo))
{
reflectionInfo = this.GenerateReflectionInfoForType(valueType);
this.reflectionInfoCache.Add(valueType, reflectionInfo);
}

return reflectionInfo;
}
}
public ReflectionInfo GetOrCreateReflectionInfo(Type valueType) => this.reflectionInfoCache.GetOrAdd(valueType, valueFactory: this.GenerateReflectionInfoForType);

private static Func<object, object> GenerateFastGetterForProperty(Type type, PropertyInfo property)
{
Expand Down