Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Async Governor - SemphoreSlim
// using System.Threading.Tasks
const int MAX_DEGREE_OF_PARALLELISM = 2;
static SemaphoreSlim _semaphore = new SemaphoreSlim(MAX_DEGREE_OF_PARALLELISM);
async void Main()
{
var tasks = Enumerable.Range(0, 10)
.Select(i => ExecTask(i))
.ToArray();
await Task.WhenAll(tasks);
Console.WriteLine("ALL DONE.");
}
async Task<int> ExecTask(int index)
{
await _semaphore.WaitAsync();
try
{
Console.WriteLine($"Task {index} starting.");
await Task.Delay(1000);
Console.WriteLine($"Task {index} done.");
return index;
}
finally
{
_semaphore.Release();
}
}
/**********
* Output *
***********
Task 0 starting.
Task 1 starting.
Task 1 done.
Task 0 done.
Task 3 starting.
Task 2 starting.
Task 2 done.
Task 3 done.
Task 4 starting.
Task 5 starting.
Task 5 done.
Task 4 done.
Task 7 starting.
Task 6 starting.
Task 6 done.
Task 7 done.
Task 8 starting.
Task 9 starting.
Task 8 done.
Task 9 done.
ALL DONE.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.