Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static async Task<TimeSpan> RunTasksAsync<T>(this IEnumerable<T> source, int maxDegreeOfParallelism, Func<T, Task> body)
- {
- SemaphoreSlim semaphore = new SemaphoreSlim(maxDegreeOfParallelism);
- List<Task> tasks = new List<Task>();
- Stopwatch stopwatch = new Stopwatch();
- stopwatch.Start();
- foreach (T item in source)
- {
- var task = Task.Run(async () =>
- {
- try
- {
- await semaphore.WaitAsync();
- await body(item);
- return true;
- }
- finally
- {
- semaphore.Release();
- }
- });
- tasks.Add(task);
- }
- await Task.WhenAll(tasks);
- stopwatch.Stop();
- return (stopwatch.Elapsed);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement