public static async Task executeParallel<T>(this IEnumerable<T> items, int limit, Func<T, Task> actionMethod)
{
var allTasks = new List<Task>(); //Store all Tasks
var activeTasks = new List<Task>();
foreach (var item in items)
{
if (activeTasks.Count >= limit)
{
var completedTask = await Task.WhenAny(activeTasks);
activeTasks.Remove(completedTask);
}
var task = actionMethod(item);
allTasks.Add(task);
activeTasks.Add(task);
}
await Task.WhenAll(allTasks); // Wait for all task to complete
}
public async Task fun(int processId)
{
await Task.Run( () =>{
Random rand = new Random();
Console.WriteLine("Processing " + processId);
Thread.Sleep(rand.Next(1500));
Console.WriteLine("Done processing - " + processId);
});
}
internal async void process(List<int> queue,int limit)
{
await queue.executeParallel(limit, fun);
}
https://www.codeproject.com/Tips/1264928/Throttling-Multiple-Tasks-to-Process-Requests-in-C