LogarithmicTimeout.cs 1.2 KB

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