From 9819c44dcccab21f6bd1949b648aced0e503ca7d Mon Sep 17 00:00:00 2001 From: Drew Tingen Date: Sun, 13 Dec 2020 16:16:57 -0500 Subject: [PATCH] fix: Fix threading issue in EnumUtils cache --- ICD.Common.Utils/EnumUtils.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/ICD.Common.Utils/EnumUtils.cs b/ICD.Common.Utils/EnumUtils.cs index df98ed5..e01c450 100644 --- a/ICD.Common.Utils/EnumUtils.cs +++ b/ICD.Common.Utils/EnumUtils.cs @@ -15,7 +15,10 @@ namespace ICD.Common.Utils public static class EnumUtils { private static readonly Dictionary s_EnumValuesCache; + private static readonly SafeCriticalSection s_EnumValuesCacheSection; + private static readonly Dictionary> s_EnumFlagsCache; + private static readonly SafeCriticalSection s_EnumFlagsCacheSection; /// /// Static constructor. @@ -23,7 +26,9 @@ namespace ICD.Common.Utils static EnumUtils() { s_EnumValuesCache = new Dictionary(); + s_EnumValuesCacheSection = new SafeCriticalSection(); s_EnumFlagsCache = new Dictionary>(); + s_EnumFlagsCacheSection = new SafeCriticalSection(); } #region Validation @@ -59,6 +64,7 @@ namespace ICD.Common.Utils /// public static bool IsEnum(T value) { + // ReSharper disable once CompareNonConstrainedGenericWithNull return value != null && IsEnumType(value.GetType()); } @@ -168,7 +174,7 @@ namespace ICD.Common.Utils throw new ArgumentNullException("type"); // Reflection is slow and this method is called a lot, so we cache the results. - return s_EnumValuesCache.GetOrAddNew(type, () => GetValuesUncached(type).ToArray()); + return s_EnumValuesCacheSection.Execute(() => s_EnumValuesCache.GetOrAddNew(type, () => GetValuesUncached(type).ToArray())); } /// @@ -346,10 +352,10 @@ namespace ICD.Common.Utils /// public static IEnumerable GetFlags(Type type, object value) { - return s_EnumFlagsCache.GetOrAddNew(type, () => new Dictionary()) + return s_EnumFlagsCacheSection.Execute(() => s_EnumFlagsCache.GetOrAddNew(type, () => new Dictionary()) .GetOrAddNew(value, () => GetValues(type) .Where(f => HasFlag(value, f)) - .ToArray()); + .ToArray())); } ///