I'm using a semaphore to spread work onto a fixed amount of threads and after all of the work is done i want to proceed all of the results. I'm currently waiting until the CurrentCount of the semaphore is back to the original limit however I'm curious if there is a better approach to wait until no more work is left/all threads are back available?
var semaphore = new SemaphoreSlim(5, 5);
foreach (var site in foundSites)
{
await semaphore.WaitAsync();
_ = Task.Run(async () =>
{
<PROCESSING CODE>
}).ContinueWith(task => semaphore.Release());
}
while (semaphore.CurrentCount < 5)
{
await Task.Delay(1);
}
<PROCESSING OF ALL PROCESSED ITEMS>