Note: this basically just illustrates me being confused about async
. Maybe it can help other confused people.
I was doing some HttpClient
async
await
requests in a loop, and I noticed that the requests seemed to be done sequentially (it waited for the result before starting next iteration).
So I tried a test using await Task.Delay
in a loop instead of web requests.
Maybe I've lost the plot, but I would have thought that await
in a loop could result in the next iteration of the loop starting while the result is awaited. Instead it seems that everything executes in sequence:
int _iterations = 1000;
int _count= 0;
Stopwatch _stopwatch = new Stopwatch();
_stopwatch.Start();
for (int i = 0; i < _iterations; i++)
{
Console.WriteLine("Elapsed: {0}. Calls count: {1}.", _stopwatch.Elapsed, ++_count);
await Task.Delay(5000);
Console.WriteLine("Calls count again: {0}", _count);
}
This results in:
Elapsed: 00:00:00.0000059. Calls count: 1.
Calls count again: 1
Elapsed: 00:00:05.0022733. Calls count: 2.
Calls count again: 2
Elapsed: 00:00:10.0100470. Calls count: 3.
Calls count again: 3
Elapsed: 00:00:15.0182479. Calls count: 4.
Yes, I could leave out the await
and add the returned Task
s to some array and use Task.WhenAll
. But I am surprised that await
is blocking in my loop, and that it all executes sequentially. Is this normal?
Edit: So in conclusion: I got a bit confused there. Control is returned to outside the loop at the await
. This makes sense because it mimics the synchronous analogy, but of course does not block the thread.