I have the following code:
public IEnumerable<Task> ExecuteJobs(Action[] pJobsToExecute)
{
var tasks = new Task[pJobsToExecute.Length];
for (int i = 0; i < pJobsToExecute.Length; i++)
{
//tasks[i] = new Task((index) => ProcessJob(pJobsToExecute[(int)index], (int)index), i);
//tasks[i].Start();
tasks[i] = new Task(() => ProcessJob(pJobsToExecute[i], i));
tasks[i].Start();
}
return tasks;
}
public void ProcessJob(Action jobToProcess, int index)
{
// ...
}
I need to log the order of the tasks being sent to the ProcessJob method, I use the index parameter for this. But this code:
tasks[i] = new Task(() => ProcessJob(jobs[i], i));
tasks[i].Start();
Will not give the correct order in which the actions will be executed. This code will give the correct order:
tasks[i] = new Task((index) => ProcessJob(pJobsToExecute[(int)index], (int)index), i);
tasks[i].Start();
I don't understand why this overload for Task fixes the issue. Does the i get passed to the index parameter based on actual order of execution? Or have my tests been incorrect and will this code also fail?