|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
-
- 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<EventBus>
- {
- //事件处理委托
- public delegate void EventCallBackHandle(params object[] args);
- //事件处理委托
- public delegate void EventHandle(IEvent @event, EventCallBackHandle callBack = null);
- //事件订阅者集合
- private ConcurrentDictionary<Type, List<EventHandle>> _eventHandls = new ConcurrentDictionary<Type, List<EventHandle>>();
-
- /// <summary>
- /// 事件订阅
- /// </summary>
- public void Subscribe<TEvent>(EventHandle handle)
- {
- if (!_eventHandls.ContainsKey(typeof(TEvent)))
- _eventHandls.TryAdd(typeof(TEvent), new List<EventHandle>());
- lock (_eventHandls)
- _eventHandls[typeof(TEvent)].Add(handle);
- }
-
- /// <summary>
- /// 事件退订
- /// </summary>
- public void UnSubscribe<TEvent>(EventHandle handle)
- {
- if (_eventHandls.ContainsKey(typeof(TEvent)))
- {
- if (_eventHandls[typeof(TEvent)].Contains(handle))
- {
- lock (_eventHandls)
- _eventHandls[typeof(TEvent)].Remove(handle);
- }
- }
- }
-
- /// <summary>
- /// 事件发布,不带返回
- /// </summary>
- public void Publish<TEvent>(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);
- //});
- }
- }
-
- /// <summary>
- /// 事件发布,带返回
- /// </summary>
- public void Publish<TEvent>(TEvent @event, EventCallBackHandle eventCallBack) where TEvent : IEvent
- {
- List<object> result = new List<object>();
- 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());
- }
-
- /// <summary>
- /// 事件总线释放
- /// </summary>
- public void Dispose()
- {
- _eventHandls.Clear();
- }
- }
-
- }
|