RateGate Class
Definition
Provides a synchronous, leading-edge admission gate that admits at most one invocation per fixed interval, dropping any calls that arrive while the cool-down window opened by the previous admitted call is still open.
public sealed class RateGate
- Inheritance
-
RateGate
- Inherited Members
- Extension Methods
Examples
var gate = new RateGate(TimeSpan.FromSeconds(1));
// Refreshes at most once per second regardless of call frequency.
if (gate.TryInvoke())
_ = RefreshAsync();
Remarks
RateGate is a synchronous gate: it has no await path of its own and does not queue,
schedule, or invoke any work. It is intended to guard async workflows by deciding, cheaply and without
blocking, whether a given trigger should proceed. TryInvoke() returns true when a
call is admitted and false when it falls inside the current cool-down window; the first call
after construction is always admitted. TimeUntilNext reports how long remains before the next call
would be admitted.
Timing uses the supplied TimeProvider (defaulting to System), which allows deterministic testing with a controllable provider. The type is safe to call concurrently from multiple threads. It implements leading-edge throttling only: there is no trailing invocation, queued execution, or callback.
Constructors
RateGate(TimeSpan, TimeProvider?)
Initializes a new instance of the RateGate class.
public RateGate(TimeSpan interval, TimeProvider? timeProvider = null)
Parameters
intervalTimeSpanThe minimum interval between admitted invocations.
timeProviderTimeProviderThe time provider used to measure the interval, or null to use System.
Exceptions
- ArgumentOutOfRangeException
intervalis less than or equal to zero.
Properties
TimeUntilNext
Gets the time remaining before the next invocation would be admitted.
public TimeSpan TimeUntilNext { get; }
Property Value
Methods
TryInvoke()
Attempts to admit an invocation.
public bool TryInvoke()
Returns
Applies to
| Product | Versions |
|---|---|
| .NET | 8, 10 |