Finally, with C# 10, we now have the async version of Parallel.ForEach which is Parallel.ForEachAsync.
Consider the below code.
List<string> urls = new()
{
"https://devblogs.microsoft.com/dotnet/feed",
"https://devblogs.microsoft.com/aspnet/feed",
"https://devblogs.microsoft.com/visualstudio/feed",
"https://devblogs.microsoft.com/devops/feed"
};
var client = new HttpClient();
async Task<string> Download(string url, CancellationToken cancellationToken = default)
{
HttpResponseMessage response = await client.GetAsync(url, cancellationToken);
return await response.Content.ReadAsStringAsync(cancellationToken);
}
Prior to C# 10, if we are to do a download in Parallel, most likely what we would do is something like below.
List<Task<string>> tasks = new();
foreach (var url in urls)
{
tasks.Add(Download(url));
}
List<string>? results = (await Task.WhenAll(tasks)).ToList();
// TODO: Work with results
Now we can easily use Parallel.ForEachAsync.
List<string>? results = new();
await Parallel.ForEachAsync(urls, async (url, cancellationToken) =>
{
results.Add(await Download(url, cancellationToken));
});
// TODO: Work with results
And this gives us more flexibility like we can control the ParallelOptions.
Hope this helps.
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment