Skip to content

Instantly share code, notes, and snippets.

@akatakritos
Created May 31, 2018 15:00
Show Gist options
  • Save akatakritos/13af3840c7627d293d12fbc0d69aafa3 to your computer and use it in GitHub Desktop.
Save akatakritos/13af3840c7627d293d12fbc0d69aafa3 to your computer and use it in GitHub Desktop.
Async Rate Limiting with SemaphoreSlim
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
private const int RateLimit = 5;
private static readonly Random _rng = new Random();
private static readonly SemaphoreSlim _rateLimiter = new SemaphoreSlim(RateLimit, RateLimit);
static void Main(string[] args)
{
const int NumTasks = 20;
var tasks = Enumerable.Range(1, NumTasks)
.Select(i => DoRateLimitedWork(i.ToString()))
.ToArray();
Task.WaitAll(tasks);
if (Debugger.IsAttached)
{
Console.WriteLine("Done");
Console.ReadKey(true);
}
}
private static async Task DoRateLimitedWork(string name)
{
await _rateLimiter.WaitAsync();
try
{
await DoSomeWork(name);
}
finally
{
_rateLimiter.Release();
}
}
private static async Task DoSomeWork(string workName)
{
var delay = _rng.Next(500, 3000);
Console.WriteLine($"Started {workName} for {delay}ms");
await Task.Delay(TimeSpan.FromMilliseconds(delay));
Console.WriteLine($"Ended {workName}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment