迭代异步作用域

时间:2020-02-29 21:10:30

标签: c# concurrency async-await

在以下代码块中:

static void Main(string[] args)
        {
            List<int> arr00 = new List<int>() {100, 0, 3, 8, 21};
            int index = 0;
            int tasks = 0;
            foreach (int num in arr00)
            {
                var innerIndex = index;
                Task.Run(async () =>
                {
                    Console.WriteLine($"{index}, {innerIndex}: {num}");
                    tasks++;
                });

                index++;
            }

            while (tasks < index) { }
        }

输出为 5, 1: 0 5, 4: 21 5, 2: 3 5, 3: 8 5, 0: 100

异步任务如何保持innerIndex的正确计数,而不是提升的索引的计数?

谢谢

1 个答案:

答案 0 :(得分:0)

foreach循环开始task完成迭代,在下一次迭代中开始另一个task,依此类推。 fareach完成所有迭代并将index的值设置为5,甚至在第一个任务开始之前。因此,对于所有任务,您发现index的值为5。 现在,如果您添加一个Wait才能完成每个任务,那么indexinnerIndex的值将匹配。但是您将失去并行执行这些任务的优势。

将代码更改为:

foreach (int num in arr00)
{
    var innerIndex = index;
    Task.Run(async () =>
    {
        Console.WriteLine($"{index}, {innerIndex}: {num}");
        tasks++;
    }).Wait();  //Wait for task to complete

    index++;
}

输出:

0, 0: 100
1, 1: 0
2, 2: 3
3, 3: 8
4, 4: 21