A thread-safe utility designed to manage the rate at which tasks are executed, ensuring they are not run more frequently than a specified interval.
RateLimitingExecutor
is ideal for interacting with rate-limited APIs or throttling the execution of resource-intensive tasks.
Tasks
, ValueTasks
, and Actions
are executed one at a time. If the defined interval between executions has passed, the task runs immediately; otherwise, it waits until the interval elapses before proceeding.
-
This is not a background queue processor. Each method awaits the result of the asynchronous operation before continuing.
-
Asynchronous methods will not block the calling thread, but synchronous methods will block execution until it completes.
Check out the singleton factory implementation: Soenneker.Utils.RateLimiting.Factory
dotnet add package Soenneker.Utils.RateLimiting.Executor
Below is an example demonstrating how to use the RateLimitingExecutor to execute a series of tasks while maintaining a rate limit.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Soenneker.Utils.RateLimiting.Executor;
public class Program
{
public static async Task Main(string[] args)
{
var rateLimitingExecutor = new RateLimitingExecutor(TimeSpan.FromSeconds(2));
for (int i = 0; i < 5; i++)
{
await rateLimitingExecutor.Execute(async ct =>
{
Console.WriteLine($"Executing Task {i + 1} at {DateTime.Now:HH:mm:ss}");
await Task.Delay(100); // Simulate some work
});
}
}
}
Executing Task 1 at 14:00:00
Executing Task 2 at 14:00:02
Executing Task 3 at 14:00:04
Executing Task 4 at 14:00:06
Executing Task 5 at 14:00:08