I thought I understand the async-await
pattern in C#
but today I've found out I really do not.
In a simple code snippet like this. I have System.Net.ServicePointManager.DefaultConnectionLimit = 1000;
defined already.
public static async Task Test()
{
HttpClient client = new HttpClient();
string str;
for (int i = 1000; i <= 1100; i++)
str = await client.GetStringAsync($"https://en.wikipedia.org/wiki/{i1}");
}
What does await
do here? Initially I thought since this is in async-await pattern, it means basically HttpClient will initiate all HTTP GET calls in a multi-threaded fashion, i.e. basically all the Urls should be fetched at once.
But when I'm using Fiddler to analyze the behavior I've found it really fetches the URLs sequentially.
I need to change it to this to make it work:
public static async Task<int> Test()
{
int ret = 0;
HttpClient client = new HttpClient();
List<Task> taskList = new List<Task>();
for (int i = 1000; i <= 1100; i++)
{
var i1 = i;
var task = Task.Run(() => client.GetStringAsync($"https://en.wikipedia.org/wiki/{i1}"));
taskList.Add(task);
}
Task.WaitAll(taskList.ToArray());
return ret;
}
This time the URLs are fetched in parallel. So what does the await
keyword really do in the first code snippet?