I have a List of objects. I need to make a call to a method of every item in that list. The method is a complex one and it takes time to complete. I am searching a way to call every method in a different thread and then wait for all to finish.
Here is my actual approach (is not working right now):
List<Task> TaskList = new List<Task>();
foreach (ComplexObject co in population)
{
TaskList.Add(Task.Run(() => co.ComplexTask()));
}
Task.WaitAll(TaskList.ToArray());
Right now I'am getting exceptions in the ComplexTask:
I can execute the ComplexMethod synchronously without errors.
I assume that I'm making mistakes and I need help with the task/await usage.
Thanks.
Edit:
ComplexTask:
public int ComplexTask()
{
int maquinaCubierta = 100;
int maquinasNoCubierta = -100;
int empleadoHabitual = 50;
int empleadoNoHabitual = 25;
int empleadoAVarios = 15;
int empleadoCambioTurno = -75;
int ett = -10;
fitness = 0;
bool perfecto = true;
procesarCalendario();
for (int dia = 0; dia < 5; dia++)
{
for (int turno = 0; turno < 3; turno++)
{
foreach (String key in asignaciones[dia][turno].Keys)
{
if (asignaciones[dia][turno][key] == null)
{
if (puestosSemana[dia][turno][0].Contains(key))
{
fitness += maquinaCubierta + ett;
}
else
{
fitness += maquinasNoCubierta;
perfecto = false;
}
}
else if (asignaciones[dia][turno][key].kPuesto == key)
{
fitness += maquinaCubierta;
fitness += asignaciones[dia][turno][key].kPuesto == key ? empleadoHabitual : empleadoNoHabitual;
if (asignaciones[dia][turno][key].turno != turno + 1)
{
fitness += empleadoCambioTurno;
perfecto = false;
}
}
}
fitness += empleadoAVarios * empleadosSinAsignacion[dia][turno].Count;
}
}
if(perfecto)
{
fitness = int.MaxValue;
}
return fitness;
}