Skip to content

Instantly share code, notes, and snippets.

@markvincze
Created September 27, 2018 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markvincze/58c9707891870b53aeabe13f9647d995 to your computer and use it in GitHub Desktop.
Save markvincze/58c9707891870b53aeabe13f9647d995 to your computer and use it in GitHub Desktop.
Async parallel processing
var runningTasks = new ConcurrentDictionary<Task, string>();
var maxDegreeOfParallelism = 5;
var semaphore = new SemaphoreSlim(maxDegreeOfParallelism);
foreach (var job in jobs)
{
await semaphore.WaitAsync();
var task = ProcessAsync(job);
runningTasks.TryAdd(task, "");
await task.ContinueWith(t =>
{
runningTasks.TryRemove(t, out _);
semaphore.Release();
});
}
await Task.WhenAll(runningTasks.Keys.ToArray());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment