StateMachineWrap.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Runtime.CompilerServices;
  4. namespace ET
  5. {
  6. public interface IStateMachineWrap
  7. {
  8. Action MoveNext { get; }
  9. void Recycle();
  10. }
  11. public class StateMachineWrap<T>: IStateMachineWrap where T: IAsyncStateMachine
  12. {
  13. private static readonly ConcurrentQueue<StateMachineWrap<T>> queue = new();
  14. public static StateMachineWrap<T> Fetch(ref T stateMachine)
  15. {
  16. if (!queue.TryDequeue(out var stateMachineWrap))
  17. {
  18. stateMachineWrap = new StateMachineWrap<T>();
  19. }
  20. stateMachineWrap.StateMachine = stateMachine;
  21. return stateMachineWrap;
  22. }
  23. public void Recycle()
  24. {
  25. if (queue.Count > 1000)
  26. {
  27. return;
  28. }
  29. queue.Enqueue(this);
  30. }
  31. private readonly Action moveNext;
  32. public Action MoveNext
  33. {
  34. get
  35. {
  36. return this.moveNext;
  37. }
  38. }
  39. private T StateMachine;
  40. private StateMachineWrap()
  41. {
  42. this.moveNext = this.Run;
  43. }
  44. private void Run()
  45. {
  46. this.StateMachine.MoveNext();
  47. }
  48. }
  49. }