Reputation: 343
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.
Upvotes: 2
Views: 83
Reputation: 8595
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]))
}
Upvotes: 1
Reputation: 4230
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
Upvotes: 6