using Serilog; namespace DispenserCommon.Events; /// /// 事件总线 /// /// public abstract class EventBus { private static readonly Dictionary> Subscribers = new(); /// /// 添加订阅 /// /// /// public static void AddEventHandler(EventType type, Delegate action) { if (Subscribers.TryGetValue(type, out var subscribers)) { var any = subscribers.Any(item => item.Equals(action)); if (!any) subscribers.Add(action); } else { Subscribers.Add(type, [action]); } } /// /// 移除订阅逻辑 /// /// 事件类型 /// 回调方法 public static void RemoveEventHandler(EventType type, Delegate action) { if (!Subscribers.TryGetValue(type, out var handlers)) return; handlers.Remove(action); } /// /// 发布事件 /// /// /// public static void Publish(EventType type, T data) { if (!Subscribers.TryGetValue(type, out var subscribers)) return; // 创建一个副本,避免在回调中修改订阅列表导致迭代异常 var actions = subscribers.ToList(); foreach (var action in actions) try { action.DynamicInvoke(type, data); } catch (Exception e) { Log.Error(e, e.Message); } } }