Skip to content

Instantly share code, notes, and snippets.

@Ilchert
Last active May 29, 2025 18:25
Show Gist options
  • Save Ilchert/23cb8c8c064ae4640d8ff416301c2dba to your computer and use it in GitHub Desktop.
Save Ilchert/23cb8c8c064ae4640d8ff416301c2dba to your computer and use it in GitHub Desktop.
Throttle
await using var limiter = new FixedWindowRateLimiter(new FixedWindowRateLimiterOptions() { Window = TimeSpan.FromSeconds(1), PermitLimit = 1, AutoReplenishment = true, QueueLimit = 1 });
var source = Ints();
await foreach (var item in Debounce(source, limiter))
{
Console.WriteLine($"{DateTime.Now} {item}");
}
static async IAsyncEnumerable<int> Ints()
{
for (int i = 0; i < 106; i += 5)
{
await Task.Delay(i * 10);
yield return i;
}
}
static async IAsyncEnumerable<T> Debounce<T>(IAsyncEnumerable<T> source, RateLimiter limiter)
{
var ch = Channel.CreateBounded<T>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true, SingleWriter = true });
_ = EnumerateSource(source);
while (true)
{
using var lease = await limiter.AcquireAsync();
if (await ch.Reader.WaitToReadAsync() && ch.Reader.TryRead(out var item))
yield return item;
else
break;
}
async Task EnumerateSource(IAsyncEnumerable<T> source)
{
await foreach (var item in source)
ch.Writer.TryWrite(item);
ch.Writer.Complete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment