MoshPit.cs 2.3 KB

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