c# - Is creating tasks via a for loop different to creating them individually? -
the problem having seems related task creation. after using loop populate task array, , starting them within separate loop, results, although consistent, wrong. however, if populate array individually, start each task within loop, fine. can 1 offer me advice?
for example, problematic:
int c = 1; (int = 1; <= 4; i++) { taskarray[i-1] = new task(() => calculaterows(c, true)); c = c + 2; } foreach (task t in taskarray) t.start();
but works fine:
taskarray[0] = new task(() => calculaterows(1, true)); taskarray[1] = new task(() => calculaterows(3, true)); taskarray[2] = new task(() => calculaterows(5, true)); taskarray[3] = new task(() => calculaterows(7, true)); foreach (task t in taskarray) t.start();
the problem lambda expression captures c
- variable c
, not value @ time of task creation. time start tasks, c
9. if started them within loop, there's still no guarantee code in lambda expression start execute before change c
.
to fix this, can use separate local variable each iteration of loop:
int c = 1; (int = 1; <= 4; i++) { int temp = c; taskarray[i-1] = new task(() => calculaterows(temp, true)); c = c + 2; } foreach (task t in taskarray) { t.start(); }
or bypass c
entirely , compute temp
i
:
for (int = 1; <= 4; i++) { int temp = * 2 - 1; taskarray[i-1] = new task(() => calculaterows(temp, true)); } foreach (task t in taskarray) { t.start(); }
do need these separate tasks though? use parallel.for
instead? or perhaps enumerable.range
suggested in comments:
var tasks = enumerable.range(1, 4) .select(x => new task(() => calculaterows(x * 2 - 1, true) .toarray(); foreach (task t in tasks) { t.start(); }
Comments
Post a Comment