My understanding about thread safe method parameters is: Parameters passed into a method by value are delivered as copies of the data that was given in the arguments to the method call, so they are unique to that method call and cannot be changed by any other task. Reference parameters, conversely, are susceptible to change by code running in other tasks.
With that said, It is not perfectly clear to me why the following code (without making a local copy of the loop counter) returns the same number in every thread.
static void ExampleFunc(int i) =>
Console.WriteLine("task " + i);
for (int i = 0; i < 10; i++)
{
int taskN = i; //local copy instead of i
Task.Run(() => Func(i));
}
The actual output is: task 10 ten times
I get the correct output (task 1 to 10) by passing taskN instead of i.
I expected the same result since I'm passing a type value parameter.