Messager.cs 837 B

1234567891011121314151617181920212223242526272829303132
  1. using System;
  2. using System.Collections.Concurrent;
  3. namespace SHJX.Service.Common.Utils
  4. {
  5. public static class Messager<T> where T : class
  6. {
  7. private static readonly ConcurrentDictionary<string, Action<T>> Actions = new();
  8. /// <summary>
  9. /// 注册消息
  10. /// </summary>
  11. public static void Register(string name, Action<T> action)
  12. {
  13. if (!Actions.ContainsKey(name))
  14. {
  15. Actions.TryAdd(name, action);
  16. }
  17. Actions[name] = action;
  18. }
  19. /// <summary>
  20. /// 消息发送
  21. /// </summary>
  22. public static void Send(string name, T t = null)
  23. {
  24. if (Actions.TryGetValue(name, out Action<T> service))
  25. {
  26. service?.Invoke(t);
  27. }
  28. }
  29. }
  30. }