Reputation: 9724
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);
...
}
Question: On button click, at the 1st iteration of the for loop, when the await keyword in the MyAsyncMtd
is encountered, then I know that the control goes to the caller. The caller in this case is the button click method. Does this mean that the next iteration gets processed while waiting (Task.Delay) on the 1st iteration's Task.Delay (in other words - does await return Task to the caller?)? or what happens exactly?
Upvotes: 2
Views: 209
Reputation: 1502446
The next iteration occurs without any waiting - because you haven't awaited the task yet. So you'll very quickly go through the foreach
loop and reach the Task.WhenAll
. That will complete when all the tasks have completed, i.e. 1 second after the final Task.Delay(1000)
call was executed.
The await
operator doesn't always trigger the method returning immediately - it only does so when the operand isn't already completed. For example, consider this code:
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");
}
I'd expect the output to be:
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
Upvotes: 3