From eff69a6fe83e79188c048d2c8df2c3655265ddaa Mon Sep 17 00:00:00 2001 From: David Hall Date: Thu, 6 Jun 2024 11:11:51 -0600 Subject: [PATCH] Fixed bug affecting HRESULT.ToString in StaticFieldHasValue.TryGetFieldName --- PInvoke/Shared/FieldValueHash.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/PInvoke/Shared/FieldValueHash.cs b/PInvoke/Shared/FieldValueHash.cs index 91772b04..bfb79e12 100644 --- a/PInvoke/Shared/FieldValueHash.cs +++ b/PInvoke/Shared/FieldValueHash.cs @@ -8,6 +8,7 @@ namespace Vanara.PInvoke; /// Gets a static field's name from its value and caches the list for faster lookups. public static class StaticFieldValueHash { + private static readonly object cacheLock = new(); private static readonly Dictionary<(Type, Type), IDictionary> cache = []; /// Adds the seqence of field values to the associated cache. @@ -63,7 +64,12 @@ public static class StaticFieldValueHash 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, null)); - cache.Add(tt, hash); + lock (cacheLock) +#if NET5_0_OR_GREATER || NETCOREAPP + cache.TryAdd(tt, hash); +#else + { if (!cache.ContainsKey(tt)) cache.Add(tt, hash); } +#endif } var ret = hash.TryGetValue(value.GetHashCode(), out var t); fieldName = t.Item1;