EventSuppressor.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Immutable;
  4. using System.Linq;
  5. using System.Runtime.CompilerServices;
  6. namespace InABox.Core
  7. {
  8. public class EventSuppressor : IDisposable
  9. {
  10. private static Dictionary<Enum, int> _cache = new Dictionary<Enum, int>();
  11. private Enum[] _scopes;
  12. public static ImmutableDictionary<Enum, int> Cache() => _cache.ToImmutableDictionary();
  13. public EventSuppressor(params Enum[] scopes)
  14. {
  15. _scopes = scopes;
  16. foreach (var scope in scopes)
  17. {
  18. _cache.TryGetValue(scope, out int count);
  19. _cache[scope] = count + 1;
  20. }
  21. }
  22. public void Dispose()
  23. {
  24. foreach (var scope in _scopes)
  25. {
  26. if (_cache.TryGetValue(scope, out int count))
  27. {
  28. if (count <= 1)
  29. _cache.Remove(scope);
  30. else
  31. _cache[scope] = count - 1;
  32. }
  33. }
  34. }
  35. public static bool IsSet(Enum scope) => _cache.TryGetValue(scope, out int count) && (count > 0);
  36. public static EventSuppressor All<T>() where T : Enum
  37. {
  38. var scopes = Enum.GetValues(typeof(T)).Cast<Enum>().ToArray();
  39. return new EventSuppressor(scopes);
  40. }
  41. }
  42. }