123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- using Microsoft.Extensions.Logging;
- namespace WarcViewerBlazorWinForm.Library.EventBus
- {
- public abstract class InProcessEventBusBase(ILogger<InProcessEventBusBase> logger) : IEventBus
- {
- private readonly Dictionary<Type, HashSet<Delegate>> _dicTypeToHandlers = new();
- public bool Subscript<T>(Action<T> callBack)
- {
- var type = typeof(T);
- lock (_dicTypeToHandlers)
- {
- if (!_dicTypeToHandlers.TryGetValue(type, out var handlers))
- {
- handlers = _dicTypeToHandlers[type] = new();
- }
- return handlers.Add(callBack); // 忽略重复
- }
- }
- public bool UnSubscript<T>(Action<T> callBack)
- {
- lock (_dicTypeToHandlers)
- {
- if (_dicTypeToHandlers.TryGetValue(typeof(T), out var handlers))
- {
- var unSubscript = handlers.Remove(callBack);
- if (handlers.Count == 0) _dicTypeToHandlers.Remove(typeof(T));
- return unSubscript;
- }
- return false;
- }
- }
- public bool Publish<T>()
- {
- PublishInternal(new AnyPublishEvent(typeof(T), default));
- return PublishInternal<T>(default);
- }
- public bool Publish<T>(T obj)
- {
- PublishInternal(new AnyPublishEvent(typeof(T), obj));
- return PublishInternal(obj);
- }
- private bool PublishInternal<T>(T eventValue)
- {
- var type = typeof(T);
- Delegate[] subscripts;
- lock (_dicTypeToHandlers)
- {
- if (!_dicTypeToHandlers.TryGetValue(type, out var handlers)) return false;
- subscripts = handlers.ToArray();
- }
- foreach (var del in subscripts)
- {
- try
- {
- ((Action<T>)del)(eventValue);
- }
- catch (Exception e)
- {
- logger.LogError(e, nameof(Publish));
- }
- }
- return true;
- }
- }
- }
|