InProcessEventBusBase.cs 1.9 KB

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