I have code like this:
var listAction = new List<Task>();
...
foreach (var symbol in chunk)
{
listAction.Add(Task.Run(() => DoBooster(symbol, ...)));
}
int failed = 0;
Task t = Task.WhenAll(listAction);
try
{
t.Wait();
}
catch { }
if (t.Status == TaskStatus.RanToCompletion)
{
Console.WriteLine("All Boosters succeeded.");
}
else if (t.Status == TaskStatus.Faulted)
{
Console.WriteLine("{0} Booster failed", failed);
}
The problem is, I want to limit the number of tasks
that run simultaneously. Ideally, I would like to say (this doesn't exist I am just saying what I would like)
maxConcurrentTasks = 4;
I would still like to loop as above and keep adding tasks
indefinitely, but I want tasks
to block if maxConcurrentTasks
is exceeded EVEN IF THERE AREA AVAILABLE cores, and when the number of tasks is below maxConcurrentTasks
, any pending tasks
are started.
So, if there are 16 symbols, only 4 are being processed at a time. When one is processed, another task that is blocking starts up but the number of running tasks never exceeds maxConcurrentTasks
, until the final symbol is processed.
Is there a way to do this?