c# - Parallel task execution order -
i have following code:
public ienumerable<task> executejobs(action[] pjobstoexecute) { var tasks = new task[pjobstoexecute.length]; (int = 0; < 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 log order of tasks being sent processjob method, use index parameter this. code:
tasks[i] = new task(() => processjob(jobs[i], i)); tasks[i].start(); will not give correct order in actions executed. code give correct order:
tasks[i] = new task((index) => processjob(pjobstoexecute[(int)index], (int)index), i); tasks[i].start(); i don't understand why overload task fixes issue. passed index parameter based on actual order of execution? or have tests been incorrect , code fail?
the problem creating closure on loop variable i , using value later on, after loop has progressed.
when creating lambda function () => processjob(jobs[i], i) compiler creates hidden reference variable i updated for loop. same reference read when processjob called part of task being executed.
the behavior see result of race condition: though starting tasks inside loop, tasks run on separate threads , threads not start executing immediately. when do start value of i has been modified (because more iterations of loop have been completed) , value read processjob "wrong".
the version index variable creates local copy of i logically separate , not modified i; copy therefore immune being changed before task has chance start. same (correct) behavior with:
var index = i; // note tasks[index] can tasks[i] -- makes no difference // because value used strictly during current loop iteration tasks[index] = new task(() => processjob(pjobstoexecute[index], index)); tasks[index].start(); creating local copy of captured variables above solution problems of type.
Comments
Post a Comment