Posts A Simple ForeachAsync
Post
Cancel

A Simple ForeachAsync

It’s just the codes from Implementing a simple ForEachAsync, part 2 but I will write it as simple as it should be

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
public static class ParallelHelper
{
    public static Task ForEachAsync<T>(this IEnumerable<T> source, int maxConcurrent, Func<T, Task> body)
    {
        return Task.WhenAll(
            from partition in Partitioner.Create(source).GetPartitions(maxConcurrent)
            select Task.Run(async delegate {
                using (partition)
                    while (partition.MoveNext())
                        await body(partition.Current);
            }));
    }
}

How to use

1
2
3
4
5
6
7
8
9
10
11
12
string[] urls = new []
{
    "https://google.com",
    "https://bing.com",
    "https://yahoo.com",
};

await ParallelHelper.ForEachAsync(urls, 5, async (url) =>
{
    WebClient client = new WebClient();
    await client.DownloadStringTaskAsync(url);
});
This post is licensed under CC BY 4.0 by the author.