In the update to the accepted answer to this stack-overflow question it is mentioned that
Semaphore may be disposed before completion of tasks and will raise exception when Release() method is called so before exiting the using block must wait for the completion of all created Tasks
How can this happen?
I'll paste the code here:
int maxConcurrency=10;
var messages = new List<string>();
using(SemaphoreSlim concurrencySemaphore = new SemaphoreSlim(maxConcurrency))
{
List<Task> tasks = new List<Task>();
foreach(var msg in messages)
{
concurrencySemaphore.Wait();
var t = Task.Factory.StartNew(() =>
{
try
{
Process(msg);
}
finally
{
concurrencySemaphore.Release();
}
});
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
}
So 1. Why is the task list needed?
And 2. In my case there is no foreach
but rather a socket is randomly accepting requests & calls the Task.Factory.StartNew
. I cannot wait for all threads to complete. Can this semaphore method still be used?