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.

WeakAction.cs 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Reflection;
  3. using Svelto.Utilities;
  4. namespace Svelto.WeakEvents
  5. {
  6. public class WeakAction<T1, T2> : WeakAction
  7. {
  8. public WeakAction(Action<T1, T2> listener)
  9. : base(listener.Target, listener.GetMethodInfoEx())
  10. {}
  11. public void Invoke(T1 data1, T2 data2)
  12. {
  13. _data[0] = data1;
  14. _data[1] = data2;
  15. Invoke_Internal(_data);
  16. }
  17. readonly object[] _data = new object[2];
  18. }
  19. public class WeakAction<T> : WeakActionBase
  20. {
  21. public WeakAction(Action<T> listener)
  22. : base(listener.Target, listener.GetMethodInfoEx())
  23. {}
  24. public void Invoke(T data)
  25. {
  26. _data[0] = data;
  27. Invoke_Internal(_data);
  28. }
  29. readonly object[] _data = new object[1];
  30. }
  31. public class WeakAction : WeakActionBase
  32. {
  33. public WeakAction(Action listener) : base(listener)
  34. {}
  35. public WeakAction(object listener, MethodInfo method) : base(listener, method)
  36. {}
  37. public void Invoke()
  38. {
  39. Invoke_Internal(null);
  40. }
  41. }
  42. public abstract class WeakActionBase
  43. {
  44. protected readonly DataStructures.WeakReference<object> ObjectRef;
  45. protected readonly MethodInfo Method;
  46. public bool IsValid
  47. {
  48. get { return ObjectRef.IsValid; }
  49. }
  50. protected WeakActionBase(Action listener)
  51. : this(listener.Target, listener.GetMethodInfoEx())
  52. {}
  53. protected WeakActionBase(object listener, MethodInfo method)
  54. {
  55. ObjectRef = new DataStructures.WeakReference<object>(listener);
  56. Method = method;
  57. if (method.IsCompilerGenerated() == true)
  58. throw new ArgumentException("Cannot create weak event to anonymous method with closure.");
  59. }
  60. protected void Invoke_Internal(object[] data)
  61. {
  62. if (ObjectRef.IsValid)
  63. Method.Invoke(ObjectRef.Target, data);
  64. else
  65. Utility.Console.LogWarning("Target of weak action has been garbage collected");
  66. }
  67. }
  68. }