using Microsoft.Extensions.Logging; namespace WarcViewerBlazorWinForm.Library.EventBus { public abstract class InProcessEventBusBase(ILogger logger) : IEventBus { private readonly Dictionary> _dicTypeToHandlers = new(); public bool Subscript(Action callBack) { var type = typeof(T); lock (_dicTypeToHandlers) { if (!_dicTypeToHandlers.TryGetValue(type, out var handlers)) { handlers = _dicTypeToHandlers[type] = new(); } return handlers.Add(callBack); // 忽略重复 } } public bool UnSubscript(Action callBack) { lock (_dicTypeToHandlers) { if (_dicTypeToHandlers.TryGetValue(typeof(T), out var handlers)) { var unSubscript = handlers.Remove(callBack); if (handlers.Count == 0) _dicTypeToHandlers.Remove(typeof(T)); return unSubscript; } return false; } } public bool Publish() { PublishInternal(new AnyPublishEvent(typeof(T), default)); return PublishInternal(default); } public bool Publish(T obj) { PublishInternal(new AnyPublishEvent(typeof(T), obj)); return PublishInternal(obj); } private bool PublishInternal(T eventValue) { var type = typeof(T); Delegate[] subscripts; lock (_dicTypeToHandlers) { if (!_dicTypeToHandlers.TryGetValue(type, out var handlers)) return false; subscripts = handlers.ToArray(); } foreach (var del in subscripts) { try { ((Action)del)(eventValue); } catch (Exception e) { logger.LogError(e, nameof(Publish)); } } return true; } } }