【问题标题】:Iterative async scope迭代异步范围
【发布时间】:2020-02-29 21:10:30
【问题描述】:

在以下代码块中:

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 计数,而不是提升的索引?

谢谢

【问题讨论】:

标签: c# concurrency async-await


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-05
    • 2014-02-04
    • 2019-10-07
    • 2018-05-23
    • 1970-01-01
    • 2015-03-09
    • 2021-10-22
    • 1970-01-01
    相关资源
    最近更新 更多