Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

126 lines
2.9KB

  1. using System;
  2. using System.Reflection;
  3. using System.Runtime.CompilerServices;
  4. using System.Runtime.InteropServices;
  5. //careful, you must handle the destruction of the GCHandles!
  6. namespace BetterWeakEvents
  7. {
  8. public struct WeakAction<T1, T2> : IEquatable<WeakAction<T1, T2>>
  9. {
  10. public WeakAction(Action<T1, T2> listener)
  11. {
  12. ObjectRef = GCHandle.Alloc(listener.Target, GCHandleType.Weak);
  13. #if !NETFX_CORE
  14. Method = listener.Method;
  15. #else
  16. Method = listener.GetMethodInfo();
  17. #endif
  18. }
  19. public bool Invoke(T1 data1, T2 data2)
  20. {
  21. if (ObjectRef.IsAllocated && ObjectRef.Target != null)
  22. {
  23. Method.Invoke(ObjectRef.Target, new object[] { data1, data2 });
  24. return true;
  25. }
  26. Release();
  27. return false;
  28. }
  29. public bool Equals(WeakAction<T1, T2> other)
  30. {
  31. return (Method.Equals(other.Method));
  32. }
  33. public void Release()
  34. {
  35. ObjectRef.Free();
  36. }
  37. readonly GCHandle ObjectRef;
  38. readonly MethodInfo Method;
  39. }
  40. public struct WeakAction<T> : IEquatable<WeakAction<T>>
  41. {
  42. public WeakAction(Action<T> listener)
  43. {
  44. ObjectRef = GCHandle.Alloc(listener.Target, GCHandleType.Weak);
  45. #if !NETFX_CORE
  46. Method = listener.Method;
  47. #else
  48. Method = listener.GetMethodInfo();
  49. #endif
  50. }
  51. public bool Invoke(T data)
  52. {
  53. if (ObjectRef.IsAllocated && ObjectRef.Target != null)
  54. {
  55. Method.Invoke(ObjectRef.Target, new object[] { data });
  56. return true;
  57. }
  58. Release();
  59. return false;
  60. }
  61. public bool Equals(WeakAction<T> other)
  62. {
  63. return (Method.Equals(other.Method));
  64. }
  65. public void Release()
  66. {
  67. ObjectRef.Free();
  68. }
  69. readonly GCHandle ObjectRef;
  70. readonly MethodInfo Method;
  71. }
  72. public struct WeakAction : IEquatable<WeakAction>
  73. {
  74. public WeakAction(Action listener)
  75. {
  76. ObjectRef = GCHandle.Alloc(listener.Target, GCHandleType.Weak);
  77. #if !NETFX_CORE
  78. Method = listener.Method;
  79. #else
  80. Method = listener.GetMethodInfo();
  81. #endif
  82. }
  83. public bool Invoke()
  84. {
  85. if (ObjectRef.IsAllocated && ObjectRef.Target != null)
  86. {
  87. Method.Invoke(ObjectRef.Target, null);
  88. return true;
  89. }
  90. Release();
  91. return false;
  92. }
  93. public bool Equals(WeakAction other)
  94. {
  95. return (Method.Equals(other.Method));
  96. }
  97. public void Release()
  98. {
  99. ObjectRef.Free();
  100. }
  101. readonly GCHandle ObjectRef;
  102. readonly MethodInfo Method;
  103. }
  104. }