I can't make heads or tails of the following behaviour (please see comments in code)
for (int i = 0; i < 1000; i++)
{
string debugString = String.Concat("Inside Action ", i);
Action newAction = new Action(() => { System.Console.WriteLine(debugString); });
Task.Run(newAction); // outputs: 0, 1, 2, 3 (not always exactly in this order, but this is understandable because of async execution)
Action newAction2 = new Action(() => { System.Console.WriteLine("Inside Action2 " + i); });
Task.Run(newAction2); // outputs: 1000, 1000, 1000, 1000, 1000 (...which is the value of i *after* the iteration, why?? "i" is a primitive int?!)
}
Console.ReadKey();
I don't understand the second behaviour. The variable i should be assigned to the Action as an Instance as the Action gets created. It looks like a pointer to i is created which has the value 1000 (last value of iteration) at the time the task is run...
Please explain. Thank you.