Created
February 6, 2017 12:36
-
-
Save jakkaj/293062dad89ddd728d740cd737ef07be to your computer and use it in GitHub Desktop.
Simple Parallel Task Runner from Queues
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
/*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