FastAction.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Profiling;
  5. namespace Coffee.UIParticleInternal
  6. {
  7. /// <summary>
  8. /// Base class for a fast action.
  9. /// </summary>
  10. internal class FastActionBase<T>
  11. {
  12. private static readonly InternalObjectPool<LinkedListNode<T>> s_NodePool =
  13. new InternalObjectPool<LinkedListNode<T>>(() => new LinkedListNode<T>(default), _ => true,
  14. x => x.Value = default);
  15. private readonly LinkedList<T> _delegates = new LinkedList<T>();
  16. /// <summary>
  17. /// Adds a delegate to the action.
  18. /// </summary>
  19. public void Add(T rhs)
  20. {
  21. if (rhs == null) return;
  22. Profiler.BeginSample("(COF)[FastAction] Add Action");
  23. var node = s_NodePool.Rent();
  24. node.Value = rhs;
  25. _delegates.AddLast(node);
  26. Profiler.EndSample();
  27. }
  28. /// <summary>
  29. /// Removes a delegate from the action.
  30. /// </summary>
  31. public void Remove(T rhs)
  32. {
  33. if (rhs == null) return;
  34. Profiler.BeginSample("(COF)[FastAction] Remove Action");
  35. var node = _delegates.Find(rhs);
  36. if (node != null)
  37. {
  38. _delegates.Remove(node);
  39. s_NodePool.Return(ref node);
  40. }
  41. Profiler.EndSample();
  42. }
  43. /// <summary>
  44. /// Invokes the action with a callback function.
  45. /// </summary>
  46. protected void Invoke(Action<T> callback)
  47. {
  48. var node = _delegates.First;
  49. while (node != null)
  50. {
  51. try
  52. {
  53. callback(node.Value);
  54. }
  55. catch (Exception e)
  56. {
  57. Debug.LogException(e);
  58. }
  59. node = node.Next;
  60. }
  61. }
  62. public void Clear()
  63. {
  64. _delegates.Clear();
  65. }
  66. }
  67. /// <summary>
  68. /// A fast action without parameters.
  69. /// </summary>
  70. internal class FastAction : FastActionBase<Action>
  71. {
  72. /// <summary>
  73. /// Invoke all the registered delegates.
  74. /// </summary>
  75. public void Invoke()
  76. {
  77. Invoke(action => action.Invoke());
  78. }
  79. }
  80. }