65 lines
1.7 KiB
C#
65 lines
1.7 KiB
C#
|
using Serilog;
|
||
|
|
||
|
namespace DispenserCommon.Events;
|
||
|
|
||
|
/// <summary>
|
||
|
/// 事件总线
|
||
|
/// </summary>
|
||
|
/// <typeparam name="T"></typeparam>
|
||
|
public abstract class EventBus<T>
|
||
|
{
|
||
|
private static readonly Dictionary<EventType, List<Delegate>> Subscribers = new();
|
||
|
|
||
|
/// <summary>
|
||
|
/// 添加订阅
|
||
|
/// </summary>
|
||
|
/// <param name="type"></param>
|
||
|
/// <param name="action"></param>
|
||
|
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]);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/// <summary>
|
||
|
/// 移除订阅逻辑
|
||
|
/// </summary>
|
||
|
/// <param name="type">事件类型</param>
|
||
|
/// <param name="action">回调方法</param>
|
||
|
public static void RemoveEventHandler(EventType type, Delegate action)
|
||
|
{
|
||
|
if (!Subscribers.TryGetValue(type, out var handlers)) return;
|
||
|
|
||
|
handlers.Remove(action);
|
||
|
}
|
||
|
|
||
|
/// <summary>
|
||
|
/// 发布事件
|
||
|
/// </summary>
|
||
|
/// <param name="type"></param>
|
||
|
/// <param name="data"></param>
|
||
|
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);
|
||
|
}
|
||
|
}
|
||
|
}
|