MoshPit.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. namespace qdr.fnd.core.pqueue
  2. {
  3. public class MoshPit<TContext> where TContext : class
  4. {
  5. private readonly List<Action<TContext>> _actions;
  6. private Timer? _timer;
  7. private readonly Random _random;
  8. public TContext Context { get; set; }
  9. public long Iterations { get; private set; }
  10. public TimeSpan AvgIterationDuration { get; private set; }
  11. public TimeSpan TotalDuration { get; private set; }
  12. public decimal AvgIterationPerSecond { get; private set; }
  13. public MoshPit(TContext context)
  14. {
  15. Context = context;
  16. _actions = new List<Action<TContext>>();
  17. _random = new Random();
  18. }
  19. public void AddAction(Action<TContext> action)
  20. {
  21. _actions.Add(action);
  22. }
  23. public void Start(int iterationInterval, int totalDuration)
  24. {
  25. _timer = new Timer(ExecuteRandomAction, Context, 0, iterationInterval);
  26. // Stop the _timer after the specified duration
  27. _ = new Timer((e) => _timer.Dispose(), null, totalDuration, Timeout.Infinite);
  28. Thread.Sleep(totalDuration);
  29. }
  30. private void ExecuteRandomAction(object? state)
  31. {
  32. if (state == null)
  33. throw new ArgumentNullException(nameof(state));
  34. var context = (TContext)state;
  35. if (_actions.Count > 0)
  36. {
  37. Iterations++;
  38. var index = _random.Next(_actions.Count);
  39. var startIteration = DateTime.Now;
  40. _actions[index](context);
  41. var durationIteration = DateTime.Now - startIteration;
  42. TotalDuration = TotalDuration.Add(durationIteration);
  43. AvgIterationDuration = TimeSpan.FromTicks(TotalDuration.Ticks / Iterations);
  44. if (AvgIterationDuration==TimeSpan.Zero)
  45. AvgIterationPerSecond = 0;
  46. else
  47. AvgIterationPerSecond = TimeSpan.FromSeconds(1).Ticks / (decimal)AvgIterationDuration.Ticks;
  48. }
  49. }
  50. }
  51. }