I've done a job that does several jobs. I launch a task for each job but I have to limit the number of tasks that are running in parallel. I've followed the approach explained into this post How to limit the maximum number of parallel tasks in c-sharp.
In my example, I have to run 4 jobs, but only 2 at a time. The problem is that when first 2 jobs ended, the ObjectDisposed
exception is thrown and the program ends. The goal is that it continues with the pending tasks before check the result.
Here is the piece of code to run, wait and catch the results:
Task<int>[] taskArray = new Task<int>[recorder.Channels.Count];
//recorder.Channels.Count is 4
int index = 0;
int maxTasks = 2;
using (SemaphoreSlim concurrencySemaphore = new SemaphoreSlim(maxTasks))
{
foreach (IDataChannel channel in recorder.Channels)
{
if (test(channel.Name))
{
concurrencySemaphore.Wait();
taskArray[index] = Task<int>.Factory.StartNew(() =>
{
int resTask = -1;
try
{
resTask = ProcessChannel(channel, id, filename, recorder.Name);
}
finally
{
concurrencySemaphore.Release();
}
return resTask;
});
index++;
}
}
Task.WaitAll(taskArray);
}
// Check for task results
int[] results = new int[taskArray.Length];
for (int i = 0; i < taskArray.Length; i++)
{
results[i] = taskArray[i].Result;
if (results[i] == -1)
{
res = -1;
break;
}
}
I think there is something that I don't understand. So if anyone could help me I would be appreciated.