Tuesday, September 14, 2021

C# 10.0: Introducing Parallel.ForEachAsync

Finally, with C# 10, we now have the async version of Parallel.ForEach which is Parallel.ForEachAsync.

Consider the below code.

List<stringurls = 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<stringDownload(string urlCancellationToken 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 (urlcancellationToken) =>
{
    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