using BPASmartClient.Helper; using System; using System.Collections.Concurrent; using System.Collections.Generic; /* ***********************************************  * subject 事件总线,总线入口,后续按类型分发  * author 张原川  * date   2019/6/3 15:49:03  * ***********************************************/ namespace BPASmartClient.EventBus { /// /// 事件总线 /// public class EventBus : Singleton { /// /// 事件处理委托 /// /// public delegate void EventCallBackHandle(params object[] args); /// /// 事件处理委托 /// /// /// public delegate void EventHandle(IEvent @event, EventCallBackHandle callBack = null); /// /// 事件订阅者集合 /// private ConcurrentDictionary>> _eventHandls = new ConcurrentDictionary>>(); /// /// 事件订阅 /// public void Subscribe(string id,EventHandle handle) { if (!_eventHandls.ContainsKey(id)) _eventHandls.TryAdd(id, new ConcurrentDictionary>()); if (!_eventHandls[id].ContainsKey(typeof(TEvent))) _eventHandls[id].TryAdd(typeof(TEvent), new List()); lock (_eventHandls) _eventHandls[id][typeof(TEvent)].Add(handle); } /// /// 事件退订 /// public void UnSubscribe(string id,EventHandle handle) { if (_eventHandls.ContainsKey(id)) { if (_eventHandls[id].ContainsKey(typeof(TEvent))) { if (_eventHandls[id][typeof(TEvent)].Contains(handle)) { lock (_eventHandls) _eventHandls[id][typeof(TEvent)].Remove(handle); } } } } /// /// 事件发布,不带返回 /// public void Publish(TEvent @event) where TEvent : IEvent { if (_eventHandls.ContainsKey(@event.Id)) { if (_eventHandls[@event.Id].ContainsKey(typeof(TEvent))) { for (int i = _eventHandls[@event.Id][typeof(TEvent)].Count - 1; i >= 0; i--) _eventHandls[@event.Id][typeof(TEvent)][i](@event); //_eventHandls[typeof(TEvent)].ForEach(p => //{ // p(@event); //}); } } } /// /// 事件发布,带返回 /// public void Publish(TEvent @event, EventCallBackHandle eventCallBack) where TEvent : IEvent { List result = new List(); if (_eventHandls.ContainsKey(@event.Id)) { if (_eventHandls[@event.Id].ContainsKey(typeof(TEvent))) { //_eventHandls[typeof(TEvent)].ForEach(p => //{ // p(@event, delegate (object[] args) // { // result.AddRange(args); // }); //}); for (int i = _eventHandls[@event.Id][typeof(TEvent)].Count - 1; i >= 0; i--) { _eventHandls[@event.Id][typeof(TEvent)][i](@event, delegate (object[] args) { result.AddRange(args); }); } } } eventCallBack.Invoke(result.ToArray()); } /// /// 事件总线释放 /// public void Dispose() { _eventHandls.Clear(); } } }