UserFunctionsEvents.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using DocumentFormat.OpenXml.Spreadsheet;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace MECF.Framework.Common
  9. {
  10. public interface IUserFunctions
  11. {
  12. void SwichValue(Dictionary<string, object> parameter);
  13. void ValveTouchUp(Dictionary<string, object> parameter);
  14. void MfcFlowTouchUp(Dictionary<string, object> parameter);
  15. }
  16. public static class UserFunctionsEvents
  17. {
  18. private static readonly object lockObject = new object();
  19. private static readonly Dictionary<string, Delegate> events = new Dictionary<string, Delegate>();
  20. public static void ClearAll()
  21. {
  22. events.Clear();
  23. }
  24. public static void RegisterEvent<T>(string eventName, Action<T> eventHandler)
  25. {
  26. lock (lockObject)
  27. {
  28. if (!events.ContainsKey(eventName))
  29. {
  30. events[eventName] = null;
  31. }
  32. // 获取当前事件的委托
  33. var currentDelegate = events[eventName] as Action<T>;
  34. // 检查是否已经包含该处理器
  35. if (currentDelegate != null)
  36. {
  37. // 使用 GetInvocationList() 检查处理器是否已在委托列表中
  38. if (currentDelegate.GetInvocationList().All(d => d != (Delegate)eventHandler))
  39. {
  40. // 只有当处理器不在委托列表中时才添加
  41. currentDelegate += eventHandler;
  42. events[eventName] = currentDelegate;
  43. }
  44. }
  45. else
  46. {
  47. // 如果当前没有任何处理器,直接添加
  48. currentDelegate = eventHandler;
  49. events[eventName] = currentDelegate;
  50. }
  51. }
  52. }
  53. public static void UnregisterEvent<T>(string eventName, Action<T> eventHandler)
  54. {
  55. lock (lockObject)
  56. {
  57. if (events.ContainsKey(eventName))
  58. {
  59. var currentDelegate = (Action<T>)events[eventName];
  60. currentDelegate -= eventHandler;
  61. // 如果移除后没有其他处理器,可以选择从字典中移除键
  62. if (currentDelegate == null)
  63. {
  64. events.Remove(eventName);
  65. }
  66. else
  67. {
  68. events[eventName] = currentDelegate;
  69. }
  70. }
  71. }
  72. }
  73. public static void RaiseEvent<T>(string eventName, T args)
  74. {
  75. Action<T> handler = null;
  76. lock (lockObject)
  77. {
  78. if (events.ContainsKey(eventName))
  79. {
  80. handler = events[eventName] as Action<T>;
  81. }
  82. }
  83. handler?.Invoke(args);
  84. }
  85. }
  86. }