Debouncing vs. Throttling in .NET with H.Necessaire

Run an action once after a burst of calls with Debouncer, or once per interval during the burst with Throttler.

Applies to H.Necessaire 4.0.5.

High-frequency events (keystrokes, progress callbacks, file system notifications) can swamp your code if each one triggers real work. Debouncing and throttling are the two classic cures, and H.Necessaire ships both in the core package.

Install

dotnet add package H.Necessaire

The difference

  • Debouncer waits for calm. Each call restarts a timer, and the action runs once, after no call has arrived for the whole interval.
  • Throttler keeps a steady beat. The first call runs the action right away, and while calls keep arriving the action runs again once per interval. After a full interval with no calls it stops.

Debouncer

class Debouncer
{
    Debouncer(Func<Task> asyncActionToTame, TimeSpan debounceInterval);
    Task Invoke();
    void Dispose();
}

A search-as-you-type box: run the search once the user pauses for a second.

Task SearchUsers() { /* call the API */ return Task.CompletedTask; }

var debouncedSearch = new Debouncer(SearchUsers, TimeSpan.FromSeconds(1));

async Task OnSearchTextChanged(string text)
{
    // store the text somewhere SearchUsers can read it, then:
    await debouncedSearch.Invoke();   // returns immediately; the action runs later
}

Invoke() never waits for the action; it just (re)arms the timer. Call Dispose() when the owner goes away to cancel a pending run. Note that Debouncer has a Dispose method but does not implement IDisposable, so it can't be used in a using statement.

Throttler

class Throttler
{
    Throttler(Func<Task> asyncActionToTame, TimeSpan throttleInterval);
    Task Invoke();
}

Reporting progress from a very fast loop, at most once per second:

var throttledProgress = new Throttler(ReportProgress, TimeSpan.FromSeconds(1));

foreach (string file in files)
{
    BackUp(file);
    await throttledProgress.Invoke();
}

The first Invoke() starts a repeating timer and the action fires immediately. Every further Invoke() pushes back a second timer whose only job is to stop the repeating one, so reporting ends one interval after the loop ends.

Under the hood

Both classes are built on ImAPeriodicAction (Start, StartDelayed, Stop), implemented with Task.Delay. Both constructors have an overload taking a Func<ImAPeriodicAction> factory, which is the seam for substituting a fake timer in unit tests.

Choosing

You wantUse
Act once after a burst ends (search box, auto-save)Debouncer
Act regularly during a burst (progress, live preview)Throttler

When not to use them

Neither queues calls or passes arguments: they run a parameterless action and forget how many calls arrived. If you need every event processed, use a queue (see the QD actions article) instead.