Question

Note that in the locals i = 3

As you can clearly see the highest index of the args[] is 2, however the iterator somehow gets to 3. Explanation?

Edit: The commented Thread.Sleep magically fixes the problem.

Was it helpful?

Solution

This is caused by i being declared outside of the for loop, for the entire for loop. Since there is no guarantee that the Thread is executed at that point, the value of i can change before the Thread executes. You can "resolve" this by declaring a local variable in the for loop.

//for loop ..
var localIndex = i;
var temp = new Thread(() => PrintOut(args[localIndex], IsFilePath(args[localIndex])));
temp.Start();
//for loop ..

EDIT: Also, can you please post a code snippet next time, saves me having to write out the code again :P

OTHER TIPS

First of all

for (var i = 0; i< args.Length; i++)
{
}

is equivalent to:

int i = 0;

loop:

if (i < args.Length)
{
    i++;
    goto loop;
}

so you see that i is incremented to 3 in order to check your condition.

Of course, new Thread(() => PrintOut(args[i], IsFilePath(args[i]))) is never actually called when i is 3. However, since there is only one instance of i which the loop changes on each iteration, the execution that started when i was 2 is affected when i is incremented to 3.

To fix this, you need to copy the value of i into a new variable on each loop iteration. This copy will not be updated by the for loop:

for (var i = 0; i< args.Length; i++)
{
     var copy = i;
     Thread temp = new Thread(() => PrintOut(args[copy], IsFilePath(args[copy]))
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top