Last active
May 29, 2025 18:25
-
-
Save Ilchert/23cb8c8c064ae4640d8ff416301c2dba to your computer and use it in GitHub Desktop.
Throttle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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