You should use SemaphoreSlim
. It's especially nice in the case of async operations because it has WaitAsync
that returns a task you can await
on. The first 20 will go right through, and the rest will asynchronously wait for an operation to end so they can start.
SemaphoreSlim _semaphore = new SemaphoreSlim(20);
async Task DoSomethingAsync()
{
await _semaphore.WaitAsync();
try
{
// possibly async operations limited to 20
}
finally
{
_semaphore.Release();
}
}
Usage:
for(int i=0; i < 100; i++)
{
await DoSomethingAsync();
}