Advertisement
Guest User

Untitled

a guest
Dec 12th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.99 KB | None | 0 0
  1.  
  2.         public static async Task<TimeSpan> RunTasksAsync<T>(this IEnumerable<T> source, int maxDegreeOfParallelism, Func<T, Task> body)
  3.         {
  4.             SemaphoreSlim semaphore = new SemaphoreSlim(maxDegreeOfParallelism);
  5.             List<Task> tasks = new List<Task>();
  6.  
  7.             Stopwatch stopwatch = new Stopwatch();
  8.             stopwatch.Start();
  9.  
  10.             foreach (T item in source)
  11.             {
  12.                 var task = Task.Run(async () =>
  13.                 {
  14.                     try
  15.                     {
  16.                         await semaphore.WaitAsync();
  17.  
  18.                         await body(item);
  19.                         return true;
  20.                     }
  21.                     finally
  22.                     {
  23.                         semaphore.Release();
  24.                     }
  25.                 });
  26.                 tasks.Add(task);
  27.             }
  28.             await Task.WhenAll(tasks);
  29.  
  30.             stopwatch.Stop();
  31.             return (stopwatch.Elapsed);
  32.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement