You're closing over the variable startingIndex
in your first solution. It's important to realize that closures close over variables, not over values. The method will use the value of startingIndex
when the delegate is eventually executed, which could be at some point in the distant future, instead of using the value of that variable right now. You're constantly incrementing startIndex
until it's set to a value past the end of the array, hence your index out of bounds errors when you end up executing code using that variable after all of those increments.
The smallest code change would be to simply take a copy of the variable inside of the loop that won't change ever. Then close over that variable.
int index = startingIndex;
this.BeginInvoke((Action)(() =>
{
this.lsResult.Items.Add(files[index].ToString());
}));
Also note that you can greatly simplify your code by having the file system recursively traverse itself. Just use Directory.GetFiles(searchPath, "*.*", SearchOption.AllDirectories)
instead of explicitly handling the recursion yourself, then you can just loop through those files using a foreach
and add each file to the UI.