using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace guoke
{
///
/// 通用事件参数类,继承自 EventArgs,用于传递事件相关的消息和数据。
///
public class GeneralEventArgs : EventArgs
{
///
/// 获取或设置事件相关的消息。
///
public string Message { get; set; }
///
/// 获取或设置事件相关的数据。
///
public object Data { get; set; }
///
/// 初始化 GeneralEventArgs 类的新实例。
///
/// 事件相关的消息。
/// 事件相关的数据。
public GeneralEventArgs(string message, object data)
{
Message = message;
Data = data;
}
}
///
/// 事件字典,用于管理和触发事件。
///
/// 事件参数的类型,必须继承自 EventArgs。
public class EventService where TEventArgs : EventArgs
{
// 使用并发字典来存储事件,减少锁的使用
private readonly ConcurrentDictionary> _events = new ConcurrentDictionary>();
private readonly ConcurrentDictionary> _asyncEvents = new ConcurrentDictionary>();
private LogService log;
public EventService(LogService logService)
{
log = logService;
}
///
/// 验证事件名称和处理程序是否有效。
///
/// 事件名称。
/// 事件处理程序。
private bool ValidateEventParams(string eventName, Delegate handler)
{
if (string.IsNullOrEmpty(eventName))
{
log.Warn($"事件名称不能为 null 或空字符串");
return false;
}
if (handler == null)
{
log.Warn($"事件处理程序不能为 null");
return false;
}
return true;
}
///
/// 验证事件名称和事件参数是否有效。
///
/// 事件名称。
/// 事件参数。
private bool ValidateTriggerParams(string eventName, TEventArgs e)
{
if (string.IsNullOrEmpty(eventName))
{
log.Warn($"事件名称不能为 null 或空字符串");
return false;
}
return true;
}
///
/// 添加同步事件处理程序。
///
/// 事件名称,不能为 null 或空字符串。
/// 事件回调方法,不能为 null。
public void AddEventHandler(string eventName, EventHandler handler)
{
// 参数验证
if (ValidateEventParams(eventName, handler))
{
// 使用并发字典的 AddOrUpdate 方法来添加或更新事件处理程序
_events.AddOrUpdate(eventName, handler, (key, existingHandler) => existingHandler + handler);
log.Info($"添加同步事件:[{eventName}]成功");
}
else
log.Warn($"添加同步事件:[{eventName}]失败");
}
///
/// 添加异步事件处理程序。
///
/// 事件名称,不能为 null 或空字符串。
/// 异步事件回调方法,不能为 null。
public void AddAsyncEventHandler(string eventName, Func