I am actually reading some topics about the Task Parallel Library and the asynchronous programming with async and await. The book \"C# 5.0 in a Nutshell\" states that when await
The call of the 'GetPrimesCountAsync' method will be enqueued and executed on a pooled thread.
No. await
does not initiate any kind of background processing. It waits for existing processing to complete. It is up to GetPrimesCountAsync
to do that (e.g. using Task.Run
). It's more clear this way:
var myRunningTask = GetPrimesCountAsync();
await myRunningTask;
The loop only continues when the awaited task has completed. There is never more than one task outstanding.
So how does the CLR ensure that the requests will be processed in the order they were made?
The CLR is not involved.
I doubt that the compiler simply transforms the code into the above manner, since this would decouple the 'GetPrimesCountAsync' method from the for loop.
The transform that you shows is basically right but notice that the next loop iteration is not started right away but in the callback. That's what serializes execution.