This is a question on an answer given in this question:
How and When to use `async` and `await`
The answer was this: https://stackoverflow.com/a/31479502/1164004
To have a complete question I will also copy paste the answer:
Here is a quick console program to make it clear to those who follow. The "TaskToDo" method is your long running method that you want to make async. Making it run Async is done by the TestAsync method. The test loops method just runs through the "TaskToDo" tasks and runs them Async. You can see that in the results because they don't complete in the same order from run to run - they are reporting to the console UI thread when they complete. Simplistic, but I think the simplistic examples bring out the core of the pattern better than more involved examples:
class Program
{
static void Main(string[] args)
{
TestLoops();
Console.Read();
}
private static async void TestLoops()
{
for (int i = 0; i < 100; i++)
{
await TestAsync(i);
}
}
private static Task TestAsync(int i)
{
return Task.Run(() => TaskToDo(i));
}
private async static void TaskToDo(int i)
{
await Task.Delay(10);
Console.WriteLine(i);
}
}
Now for my part: As for my understanding, an await
call means that if the task is over, the code will continue. if its not, it will return to the calling context until the task finishes. If that's the case then why isn't it correct to say that in the program above, the first iteration of the loop will return to the main
method's context until the task is finished and only then will the next iteration of the for loop be carried out and continue in that manner for all iteration of the loop? If it waits for the first one to end and then the 2nd and then 3rd and so on, how can it be that the tasks will not finish in the natural order?