1

I have asynchronous method which for purpose of this question can be shortened to syntax like this:

 public async Task<int> PositiveParallelAnticipation()
    {
        //some operations
        List<List<MatchResult>> ranges = SplitRange(possibilityList, 4);
        var tasks = new List<Task<int>>();
        for (int i = 0; i < ranges.Count; i++)
        {
            //some more operations
            //!here is the problem!
            tasks.Add(Task.Run(() => PositiveAnticipationLoop(new Team(target), currWorkingTeamList, currworkingMatchList, startingPossibility, ranges[i])));
        }
        int[] results = await Task.WhenAll(tasks);
        return results.Max();
    }

And when I run it in debug mode it's all good but when I do it without debugging it throws error like this (when trying to get ranges[i]):

Index was outside the bounds of the array."

What am I missing? And btw I don't mutate ranges list and don't increment or decrement i in any operation which is not included here.

Gustaw Ohler
  • 53
  • 2
  • 6
  • You need to capture the index in a variable that is local to the inside of the for loop `var index = i;` and use that in the `Task.Run`. That way you capture a different variable with different values instead of the single one that's being mutated. – juharr Jul 02 '20 at 20:12

0 Answers0