Skip to content

Commit

Permalink
Addressed multi-thread issues with StaticFieldValueHash (#419)
Browse files Browse the repository at this point in the history
  • Loading branch information
dahall committed Aug 7, 2023
1 parent dbca630 commit 0b69243
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions PInvoke/Shared/FieldValueHash.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
namespace Vanara.PInvoke
{
/// <summary>Gets a static field's name from its value and caches the list for faster lookups.</summary>
public class StaticFieldValueHash
public static class StaticFieldValueHash
{
private static Dictionary<(Type, Type), IDictionary<int, string>> cache = new Dictionary<(Type, Type), IDictionary<int, string>>();
private static readonly Dictionary<(Type, Type), IDictionary<int, string>> cache = new();

/// <summary>Tries to get the name of a static field from it's value.</summary>
/// <typeparam name="TType">The type of the type.</typeparam>
Expand All @@ -19,9 +19,12 @@ public class StaticFieldValueHash
public static bool TryGetFieldName<TType, TFieldType>(TFieldType value, out string fieldName)
{
var tt = (typeof(TType), typeof(TFieldType));
if (!cache.TryGetValue(tt, out var hash))
cache.Add(tt, hash = typeof(TType).GetFields(BindingFlags.Public | BindingFlags.Static).Where(fi => fi.FieldType == typeof(TFieldType)).Distinct(FIValueComp<TFieldType>.Default).ToDictionary(fi => fi.GetValue(null).GetHashCode(), fi => fi.Name));
return hash.TryGetValue(value.GetHashCode(), out fieldName);
lock (cache)
{
if (!cache.TryGetValue(tt, out var hash))
cache.Add(tt, hash = typeof(TType).GetFields(BindingFlags.Public | BindingFlags.Static).Where(fi => fi.FieldType == typeof(TFieldType)).Distinct(FIValueComp<TFieldType>.Default).ToDictionary(fi => fi.GetValue(null).GetHashCode(), fi => fi.Name));
return hash.TryGetValue(value.GetHashCode(), out fieldName);
}
}

private class FIValueComp<TFieldType> : IEqualityComparer<FieldInfo>
Expand All @@ -30,7 +33,7 @@ private class FIValueComp<TFieldType> : IEqualityComparer<FieldInfo>

int IEqualityComparer<FieldInfo>.GetHashCode(FieldInfo obj) => ((TFieldType)obj.GetValue(null)).GetHashCode();

public static readonly FIValueComp<TFieldType> Default = new FIValueComp<TFieldType>();
public static readonly FIValueComp<TFieldType> Default = new();
}
}
}

0 comments on commit 0b69243

Please sign in to comment.