在 await 上,当控制权转到调用者时,它是否处理 for 循环的下一次迭代(await RETURN 是一项任务吗?)?

Upon await, when control goes to the caller, then does it process the next iteration of the for loop (Does await RETURN a task?)?

private async void btnTest_Click(object sender, EventArgs e)
        {
            List<Task> lstTasks = new List<Task>();
            foreach (int val in lstItems)
            {
                lstTasks.Add(MyAsyncMtd(val));
            }
            await Task.WhenAll(lstTasks);
            ...
        }

        private async Task MyAsyncMtd(int val)
        {
            ...
            await Task.Delay(1000);
            ...
        }

问题:单击按钮时,在 for 循环的第 1 次迭代中,当遇到 MyAsyncMtd 中的 await 关键字时,我知道控制权转到了调用方。本例中的调用者是按钮点击方法。这是否意味着在第一次迭代的 Task.Delay 等待 (Task.Delay) 时处理下一次迭代(换句话说 - 等待 return 任务给来电者?)?或者到底发生了什么?

下一次迭代无需任何等待 - 因为您还没有等待任务。因此,您将很快完成 foreach 循环并到达 Task.WhenAll。这将在所有任务完成后完成,即在执行最终 Task.Delay(1000) 调用后 1 秒。

await 运算符 并不总是 触发方法立即返回 - 它仅在操作数尚未完成时才会触发。例如,考虑以下代码:

public async Task Method1()
{
    Console.WriteLine("1");
    Task task = Method2();
    Console.WriteLine("2");
    await task
    Console.WriteLine("3");
}

public async Task Method2()
{
    Console.WriteLine("a");
    await Task.FromResult(10);
    Console.WriteLine("b");
    await Task.Delay(1000);
    Console.WriteLine("c");
}

我希望输出为:

1 // Before anything else happens at all in Method1
a // Call to Method2, before the first await
b // The first await didn't need to return, because the FromResult task was complete
2 // Control returned to Method2 because the Delay task was incomplete
c // Awaiting the result of Method1 means the rest of Method1 executes
3 // All done now