Created
June 2, 2022 06:54
-
-
Save doroudi/a7ca727e45c684b8035f213e14bb8d89 to your computer and use it in GitHub Desktop.
throttling async tasks using semaphore in c#
This file contains 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
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