Skip to content

Instantly share code, notes, and snippets.

@jakkaj
Created February 6, 2017 12:36
Show Gist options
  • Save jakkaj/293062dad89ddd728d740cd737ef07be to your computer and use it in GitHub Desktop.
Save jakkaj/293062dad89ddd728d740cd737ef07be to your computer and use it in GitHub Desktop.
Simple Parallel Task Runner from Queues
/*Usage
public async Task TestParallelThings()
{
var tasks = new Queue<Func<Task>>();
for (var i = 0; i < 200; i++)
{
int c = i;
tasks.Enqueue(()=>_somFucn(c));
}
await Task.Delay(5000);
await tasks.Parallel(20);
}
async Task _somFucn(int i)
{
await Task.Delay(1000);
Debug.WriteLine("Finished" + i);
}
*/
public static class TaskHelper
{
public static async Task Parallel(this Queue<Func<Task>> queue, int parallelCount)
{
var processors = new List<Task>();
for(var i = 0; i < parallelCount; i++)
{
processors.Add(_process(queue));
}
await Task.WhenAll(processors);
}
async static Task _process(Queue<Func<Task>> queue)
{
while (queue.Count > 0)
{
var q = queue.Dequeue();
await q();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment