Table of Contents

RateGate Class

Definition

Namespace
Bodu.Threading
Assembly
Bodu.Core.dll
Package
Bodu.Core 1.0.1
Source
RateGate.cs

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

interval TimeSpan

The minimum interval between admitted invocations.

timeProvider TimeProvider

The time provider used to measure the interval, or null to use System.

Exceptions

ArgumentOutOfRangeException

interval is 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

TimeSpan

Zero when an invocation can be admitted immediately; otherwise, the remaining cool-down.

Methods

TryInvoke()

Attempts to admit an invocation.

public bool TryInvoke()

Returns

bool

true if the invocation is admitted; false if it falls within the current cool-down window.

Applies to

ProductVersions
.NET8, 10