Skip to content

Instantly share code, notes, and snippets.

@doroudi
Created June 2, 2022 06:54
Show Gist options
  • Save doroudi/a7ca727e45c684b8035f213e14bb8d89 to your computer and use it in GitHub Desktop.
Save doroudi/a7ca727e45c684b8035f213e14bb8d89 to your computer and use it in GitHub Desktop.
throttling async tasks using semaphore in c#
public async Task SaveEmployees(ICollection<EmployeeImportDto> employees)
{
// set maximum 8 concurrent tasks
var throttler = new SemaphoreSlim(initialCount: 8);
var tasks = employees.Select(async item =>
{
await throttler.WaitAsync();
try
{
await SaveEmployee(item).ConfigureAwait(false);
}
finally
{
throttler.Release();
}
});
await Task.WhenAll(tasks);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment