C# 为什么计数器走得比它应该走的更远?

C# 为什么计数器走得比它应该走的更远?,c#,for-loop,asynchronous,task,C#,For Loop,Asynchronous,Task,我有一个异步方法,为了解决这个问题,可以将其缩短为如下语法: public async Task<int> PositiveParallelAnticipation() { //some operations List<List<MatchResult>> ranges = SplitRange(possibilityList, 4); var tasks = new List<Task<i

我有一个异步方法,为了解决这个问题,可以将其缩短为如下语法:

 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();
    }
public异步任务positiveParallelActivity()
{
//一些操作
列表范围=拆分范围(可能列表,4);
var tasks=新列表();
对于(int i=0;iPositiveAnticipationLoop(新团队(目标)、currWorkingTeamList、currworkingMatchList、启动可能性、范围[i]);
}
int[]results=wait Task.WhenAll(任务);
返回results.Max();
}
当我在调试模式下运行它时,一切都很好,但是当我在不调试的情况下运行它时,它会抛出类似这样的错误(当尝试获取范围[I]时):

索引超出了数组的边界。“


我遗漏了什么?顺便说一句,我不改变范围列表,也不在此处未包含的任何操作中增加或减少I。

您需要捕获for循环内部局部变量的索引
var index=I;
并在
任务中使用它。运行
。这样您就可以使用di捕获不同的变量不同的值而不是正在变异的单个值。您需要捕获for循环内部局部变量的索引
var index=i;
,并在
任务中使用该索引。运行
。这样可以捕获具有不同值的不同变量,而不是正在变异的单个变量。