diff --git a/PInvoke/Shared/FieldValueHash.cs b/PInvoke/Shared/FieldValueHash.cs
index 8534b6ec5..f765a25d7 100644
--- a/PInvoke/Shared/FieldValueHash.cs
+++ b/PInvoke/Shared/FieldValueHash.cs
@@ -6,9 +6,9 @@
namespace Vanara.PInvoke
{
/// Gets a static field's name from its value and caches the list for faster lookups.
- public class StaticFieldValueHash
+ public static class StaticFieldValueHash
{
- private static Dictionary<(Type, Type), IDictionary> cache = new Dictionary<(Type, Type), IDictionary>();
+ private static readonly Dictionary<(Type, Type), IDictionary> cache = new();
/// Tries to get the name of a static field from it's value.
/// The type of the type.
@@ -19,9 +19,12 @@ public class StaticFieldValueHash
public static bool TryGetFieldName(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.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.Default).ToDictionary(fi => fi.GetValue(null).GetHashCode(), fi => fi.Name));
+ return hash.TryGetValue(value.GetHashCode(), out fieldName);
+ }
}
private class FIValueComp : IEqualityComparer
@@ -30,7 +33,7 @@ private class FIValueComp : IEqualityComparer
int IEqualityComparer.GetHashCode(FieldInfo obj) => ((TFieldType)obj.GetValue(null)).GetHashCode();
- public static readonly FIValueComp Default = new FIValueComp();
+ public static readonly FIValueComp Default = new();
}
}
}
\ No newline at end of file