-3

I am trying to sum all the values of a byte array using 4 tasks. So I wrote a for loop in the main method with starting and running a new task each time it loops:

for (int i = 0; i < tasks.Length; i++)
{
    Task.Run(() => Sum(i));
}

The parameter of the Sum method is portionNumber. In the Sum method, the first thing it execute is:

Console.WriteLine("I is " + i);

When I run it, it shows me:

I is 4
I is 4
I is 4
I is 4

However, if I wrote it like this:

Task.Run(() => Sum(0));
Task.Run(() => Sum(1));
Task.Run(() => Sum(2));
Task.Run(() => Sum(3));

The result prints:

I is 0
I is 1
I is 2
I is 3

My question is why? How can I run the 4 task using for loops instead of duplicating code?

Thanks alot.

Marc2001
  • 281
  • 1
  • 3
  • 12

1 Answers1

0

you are running into a lambda capture common issue. you need

for (int i = 0; i < tasks.Length; i++)
{
   var capi = i;
   Task.Run(() => Sum(capi));
}

There is an excellent discusion from eric lippert somewhere on this

https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop-variable-considered-harmful/

pm100
  • 48,078
  • 23
  • 82
  • 145