The problem is that your lambda expression is capturing the variable i
, rather than its value for that iteration of the loop.
There are two options:
Capture a copy
for (int i = 0; i < files.Length; i++)
{
int copy = i;
ThreadStart start = () => flip(files[copy]); // Braces aren't needed
...
}
Use foreach - C# 5 only!
This won't help as much in your case because you're joining on every fifth item, so you need the index, but if you didn't have that bit and if you were using C# 5, you could just use:
foreach (var file in files)
{
ThreadStart start = () => flip(file);
...
}
Note that prior to C# 5, this would have had exactly the same problem.
For more details of the problem, see Eric Lippert's blog posts (part one; part two).