LogarithmicTimeout.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #nullable disable
  2. namespace Terminal.Gui.App;
  3. /// <summary>Implements a logarithmic increasing timeout.</summary>
  4. public class LogarithmicTimeout : Timeout
  5. {
  6. /// <summary>
  7. /// Creates a new instance where stages are the logarithm multiplied by the
  8. /// <paramref name="baseDelay"/> (starts fast then slows).
  9. /// </summary>
  10. /// <param name="baseDelay">Multiple for the logarithm</param>
  11. /// <param name="callback">Method to invoke</param>
  12. public LogarithmicTimeout (TimeSpan baseDelay, Func<bool> callback)
  13. {
  14. _baseDelay = baseDelay;
  15. Callback = callback;
  16. }
  17. private readonly TimeSpan _baseDelay;
  18. private int _stage;
  19. /// <summary>Increments the stage to increase the timeout.</summary>
  20. public void AdvanceStage () { _stage++; }
  21. /// <summary>Resets the stage back to zero.</summary>
  22. public void Reset () { _stage = 0; }
  23. /// <summary>Gets the current calculated Span based on the stage.</summary>
  24. public override TimeSpan Span
  25. {
  26. get
  27. {
  28. // Calculate logarithmic increase
  29. double multiplier = Math.Log (_stage + 1); // ln(stage + 1)
  30. return TimeSpan.FromMilliseconds (_baseDelay.TotalMilliseconds * multiplier);
  31. }
  32. }
  33. }