Events.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. namespace Wayne.Lib
  3. {
  4. /// <summary>
  5. /// Contains extension methods for firing events.
  6. /// </summary>
  7. public static class Events
  8. {
  9. /// <summary>
  10. /// Fires the event if it is not null.
  11. /// </summary>
  12. /// <typeparam name="TEventArgs"></typeparam>
  13. /// <param name="eventHandler"></param>
  14. /// <param name="sender"></param>
  15. /// <param name="eventArgs"></param>
  16. public static void Fire<TEventArgs>(this EventHandler<TEventArgs> eventHandler, object sender, TEventArgs eventArgs)
  17. where TEventArgs : EventArgs
  18. {
  19. var threadSafeEventHandler = eventHandler;
  20. if (threadSafeEventHandler != null)
  21. {
  22. threadSafeEventHandler(sender, eventArgs);
  23. }
  24. }
  25. /// <summary>
  26. /// Fires the event if it is not null.
  27. /// </summary>
  28. /// <param name="eventHandler"></param>
  29. /// <param name="sender"></param>
  30. /// <param name="eventArgs"></param>
  31. public static void Fire(this EventHandler eventHandler, object sender, EventArgs eventArgs)
  32. {
  33. var threadSafeEventHandler = eventHandler;
  34. if (threadSafeEventHandler != null)
  35. {
  36. threadSafeEventHandler(sender, eventArgs);
  37. }
  38. }
  39. /// <summary>
  40. /// Fires the action if not null
  41. /// </summary>
  42. /// <param name="action"></param>
  43. public static void Fire(this Action action)
  44. {
  45. if (action != null)
  46. {
  47. action();
  48. }
  49. }
  50. /// <summary>
  51. /// Fires the action if not null
  52. /// </summary>
  53. /// <param name="action"></param>
  54. /// <param name="t"></param>
  55. public static void Fire<T>(this Action<T> action, T t)
  56. {
  57. if (action != null)
  58. {
  59. action(t);
  60. }
  61. }
  62. /// <summary>
  63. /// Fires the action if not null
  64. /// </summary>
  65. /// <param name="action"></param>
  66. /// <param name="t1"></param>
  67. /// <param name="t2"></param>
  68. public static void Fire<T1, T2>(this Action<T1, T2> action, T1 t1, T2 t2)
  69. {
  70. if (action != null)
  71. {
  72. action(t1, t2);
  73. }
  74. }
  75. /// <summary>
  76. /// Fires the action if not null
  77. /// </summary>
  78. /// <param name="action"></param>
  79. /// <param name="t1"></param>
  80. /// <param name="t2"></param>
  81. /// <param name="t3"></param>
  82. public static void Fire<T1, T2, T3>(this Action<T1, T2, T3> action, T1 t1, T2 t2, T3 t3)
  83. {
  84. if (action != null)
  85. {
  86. action(t1, t2, t3);
  87. }
  88. }
  89. }
  90. }