2

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.

Mal San
  • 35
  • 5
  • 1
    Probably, thread(`taskList[i]`) starts, then the thread that started it continue the for loop and increase the value of `i`, then thread looks for `input_list[i]`, but i just increased and is `==` to `count`, so you have `ArgumentOutOfRangeException` – Matteo Umili Aug 28 '15 at 09:15
  • 1
    Also, have a read of this: http://csharpindepth.com/Articles/Chapter5/Closures.aspx – Rob Aug 28 '15 at 09:16
  • Thanks, that really answers my question. I wasn't aware of this problem with closures. – Mal San Aug 28 '15 at 09:29

0 Answers0