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
Per the msdn documentation
The await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes. The task represents ongoing work.
That means the await operator blocks the execution of the for loop until it get a responds from the server, making it sequential.
What you can do is create all the task (so that it begins execution) and then await all of them.
Here's an example from another StackOverflow question
public IEnumerable DownloadContentFromUrls(IEnumerable urls)
{
var queue = new ConcurrentQueue();
using (var client = new HttpClient())
{
Task.WaitAll(urls.Select(url =>
{
return client.GetAsync(url).ContinueWith(response =>
{
var content = JsonConvert.
DeserializeObject>(
response.Result.Content.ReadAsStringAsync().Result);
foreach (var c in content)
queue.Enqueue(c);
});
}).ToArray());
}
return queue;
}
There's also good article in msdn that explains how to make parallel request with await.
Edit:
As @GaryMcLeanHall pointed out in a comment, you can change Task.WaitAll
to await Task.WhenAll
and add the async
modifier to make the method return asynchronously
Here's another msdn article that picks the example in the first one and adds the use of WhenAll
.