Debounce & Throttle Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Debounce & Throttle runs in O(1) time and O(1) space, in C# as in every other language.
- ✓CancellationTokenSource paired with Task.Delay is the canonical debounce: cancel the previous source, await the delay, and run if you were not cancelled.
- ✓Swap the CancellationTokenSource with Interlocked.Exchange so the debounce is lock-free, cancel and dispose the previous one, and catch OperationCanceledException as the normal superseded path rather than an error.
- ✓The C# trap: Awaiting a cancelled Task.Delay THROWS TaskCanceledException. Since the whole design cancels on every keystroke, the exception is the common case, not the exceptional one, code that lets it escape produces a flood of first-chance exceptions and, in an async void handler, an unhandled exception that terminates the process.
- ✓Each debounce cycle allocates a CancellationTokenSource and a Task.Delay timer registration, so at keystroke rate this is real garbage; the Rx Throttle operator reuses a single subscription and allocates far less.
What Debounce & Throttle actually is
Debounce & Throttle in C#: what you actually reach for
C# implementation
using System;
using System.Threading;
using System.Threading.Tasks;
public sealed class Debouncer : IDisposable
{
private readonly TimeSpan _delay;
private CancellationTokenSource? _cts;
public Debouncer(TimeSpan delay) => _delay = delay;
public void Call(Func<CancellationToken, Task> action)
{
var next = new CancellationTokenSource();
var previous = Interlocked.Exchange(ref _cts, next);
previous?.Cancel();
previous?.Dispose(); // otherwise its timer leaks
_ = RunAsync(action, next.Token);
}
private async Task RunAsync(Func<CancellationToken, Task> action, CancellationToken ct)
{
try
{
await Task.Delay(_delay, ct).ConfigureAwait(false);
await action(ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// The NORMAL path: a newer call superseded this one.
}
}
public void Dispose()
{
_cts?.Cancel();
_cts?.Dispose();
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Debounce & Throttle?
CancellationTokenSource paired with Task.Delay is the canonical debounce: cancel the previous source, await the delay, and run if you were not cancelled. System.Threading.Timer and System.Reactive's Throttle/Sample operators are the alternatives. Stopwatch.GetTimestamp is the monotonic clock for throttling.
What is the most common C# mistake when implementing Debounce & Throttle?
Awaiting a cancelled Task.Delay THROWS TaskCanceledException. Since the whole design cancels on every keystroke, the exception is the common case, not the exceptional one, code that lets it escape produces a flood of first-chance exceptions and, in an async void handler, an unhandled exception that terminates the process. Catch it explicitly and treat it as "superseded".
How does Debounce & Throttle actually perform in C#?
Each debounce cycle allocates a CancellationTokenSource and a Task.Delay timer registration, so at keystroke rate this is real garbage; the Rx Throttle operator reuses a single subscription and allocates far less. Failing to Dispose the CancellationTokenSource leaks its internal timer until finalisation, which is one of the more common slow leaks in C# UI code. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.