Last active
May 12, 2024 08:41
-
-
Save wahidustoz/6c9cde808563d9c0aa5905ece915fb6e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// <summary> | |
| /// If the service uses dbContext, make sure to get another dbContext within ForEachAsync using service provider | |
| /// </summary> | |
| /// <typeparam name="T"></typeparam> | |
| /// <param name="source"></param> | |
| /// <param name="maxDegreeOfParallelism"></param> | |
| /// <param name="body"></param> | |
| /// <returns></returns> | |
| public static Task ForEachAsync<T>(IEnumerable<T> source, int maxDegreeOfParallelism, Func<T, Task> body) | |
| { | |
| return Task.WhenAll( | |
| from partition in Partitioner.Create(source).GetPartitions(maxDegreeOfParallelism) | |
| select Task.Run(async delegate | |
| { | |
| using (partition) | |
| while (partition.MoveNext()) | |
| await body(partition.Current); | |
| })); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment