InProcessEventBusBase.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using Microsoft.Extensions.Logging;
  2. namespace WarcViewerBlazorWinForm.Library.EventBus
  3. {
  4. public abstract class InProcessEventBusBase(ILogger<InProcessEventBusBase> logger) : IEventBus
  5. {
  6. private readonly Dictionary<Type, HashSet<Delegate>> _dicTypeToHandlers = new();
  7. public bool Subscript<T>(Action<T> callBack)
  8. {
  9. var type = typeof(T);
  10. lock (_dicTypeToHandlers)
  11. {
  12. if (!_dicTypeToHandlers.TryGetValue(type, out var handlers))
  13. {
  14. handlers = _dicTypeToHandlers[type] = new();
  15. }
  16. return handlers.Add(callBack); // 忽略重复
  17. }
  18. }
  19. public bool UnSubscript<T>(Action<T> callBack)
  20. {
  21. lock (_dicTypeToHandlers)
  22. {
  23. if (_dicTypeToHandlers.TryGetValue(typeof(T), out var handlers))
  24. {
  25. var unSubscript = handlers.Remove(callBack);
  26. if (handlers.Count == 0) _dicTypeToHandlers.Remove(typeof(T));
  27. return unSubscript;
  28. }
  29. return false;
  30. }
  31. }
  32. public bool Publish<T>()
  33. {
  34. PublishInternal(new AnyPublishEvent(typeof(T), default));
  35. return PublishInternal<T>(default);
  36. }
  37. public bool Publish<T>(T obj)
  38. {
  39. PublishInternal(new AnyPublishEvent(typeof(T), obj));
  40. return PublishInternal(obj);
  41. }
  42. private bool PublishInternal<T>(T eventValue)
  43. {
  44. var type = typeof(T);
  45. Delegate[] subscripts;
  46. lock (_dicTypeToHandlers)
  47. {
  48. if (!_dicTypeToHandlers.TryGetValue(type, out var handlers)) return false;
  49. subscripts = handlers.ToArray();
  50. }
  51. foreach (var del in subscripts)
  52. {
  53. try
  54. {
  55. ((Action<T>)del)(eventValue);
  56. }
  57. catch (Exception e)
  58. {
  59. logger.LogError(e, nameof(Publish));
  60. }
  61. }
  62. return true;
  63. }
  64. }
  65. }