Jason King Team : Web Development Tags : Web Development Tips & Tricks

ForEachAsync

Jason King Team : Web Development Tags : Web Development Tips & Tricks

Ever wanted to write asynchronous code inside a foreach loop?   Well now you can with this function:

 

public static Task ForEachAsync(this IEnumerable source, int dop, Func<T, Task> body)
        {
            return Task.WhenAll(
                from partition in Partitioner.Create(source).GetPartitions(dop)
                select Task.Run(async delegate
                {
                    using (partition)
                    {
                        while (partition.MoveNext())
                        {
                            await body(partition.Current);
                        }
                    }
                }));
        }

The dop parameter allows you to specify the Degree Of Parallelism which means the maximum number of functions that will be executed at the same time (in parallel).

The function returns a Task so you need to await it. Here’s an example of how to use it:

await paymentIds.ForEachAsync(10, async paymentId =>
                {
                    var paymentBusiness = new Payments();
                    var createOrder = await paymentBusiness.CreateOrderForPaymentAsync(paymentId);
                });

 

For more information: http://blogs.msdn.com/b/pfxteam/archive/2012/03/05/10278165.aspx