PlotDirector/PlotLine/Services/QueueIdleBackoff.cs

17 lines
687 B
C#

namespace PlotLine.Services;
/// <summary>Only slows sustained empty polling. Successful work and failures restore the normal cadence.</summary>
public sealed class QueueIdleBackoff(TimeSpan normal, TimeSpan maximum)
{
private int emptyPolls;
public TimeSpan Next(bool processed, bool failed = false)
{
if (processed || failed) emptyPolls = 0;
if (processed) return TimeSpan.Zero;
if (failed) return normal;
emptyPolls = Math.Min(emptyPolls + 1, 10);
var multiplier = emptyPolls <= 8 ? 1 : emptyPolls == 9 ? 2 : 4;
return TimeSpan.FromTicks(Math.Min(normal.Ticks * multiplier, Math.Max(normal.Ticks, maximum.Ticks)));
}
}