I just encountered a strange problem in a simple for loop. I get an ArgumentOutOfRangeException when I try to access input_list[i]. input_list is a list of some objects and has two members. But i equals 2 when the exception is thrown.
var count = input_list.Count;
var taskList = new Thread[count];
for (int i = 0; i < count; i++)
{
taskList[i] = new Thread(() => SomeFunction(input_list[i]);
taskList[i].Start();
}
In the second version, I only introduced a local variable k that is used as an index for the input_list:
var count = input_list.Count;
var taskList = new Thread[count];
for (int i = 0; i < count; i++)
{
int k = i;
taskList[i] = new Thread(() => SomeFunction(input_list[k]);
taskList[i].Start();
}
This second version doesn't throw an exception.
So, how can i be 2 in this example? And why doesn't k become 2 in the same way?
I'm using version 4.6 of the .NET Framework and Visual Studio 2015.