using BPASmartClient.Bus.EventBus; using BPASmartClient.Helper; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /* ***********************************************  * subject 事件总线,总线入口,后续按类型分发  * author 张原川  * date   2019/6/3 15:49:03  * ***********************************************/ namespace LandStation.Bus { 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(EventHandle handle) { if (!_eventHandls.ContainsKey(typeof(TEvent))) _eventHandls.TryAdd(typeof(TEvent), new List()); lock (_eventHandls) _eventHandls[typeof(TEvent)].Add(handle); } /// /// 事件退订 /// public void UnSubscribe(EventHandle handle) { if (_eventHandls.ContainsKey(typeof(TEvent))) { if (_eventHandls[typeof(TEvent)].Contains(handle)) { lock (_eventHandls) _eventHandls[typeof(TEvent)].Remove(handle); } } } /// /// 事件发布,不带返回 /// public void Publish(TEvent @event) where TEvent : IEvent { if (_eventHandls.ContainsKey(typeof(TEvent))) { for (int i = _eventHandls[typeof(TEvent)].Count - 1; i >= 0; i--) _eventHandls[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(typeof(TEvent))) { //_eventHandls[typeof(TEvent)].ForEach(p => //{ // p(@event, delegate (object[] args) // { // result.AddRange(args); // }); //}); for (int i = _eventHandls[typeof(TEvent)].Count - 1; i >= 0; i--) { _eventHandls[typeof(TEvent)][i](@event, delegate (object[] args) { result.AddRange(args); }); } } eventCallBack.Invoke(result.ToArray()); } /// /// 事件总线释放 /// public void Dispose() { _eventHandls.Clear(); } } }