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.