Skip to content

Instantly share code, notes, and snippets.

@nitinjs
Created September 27, 2018 10:22
Show Gist options
  • Save nitinjs/52dc9a689332c5440e47ebcd2b2c7926 to your computer and use it in GitHub Desktop.
Save nitinjs/52dc9a689332c5440e47ebcd2b2c7926 to your computer and use it in GitHub Desktop.
Processing large number of items in parallel
//Task Parallel library dataflow can be obtained by nuget: https://www.nuget.org/packages/System.Threading.Tasks.Dataflow/
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
Action<int> an = n => {
//add your processing logic here
Console.WriteLine(n);
};
var options = new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded
};
var actionBlock = new ActionBlock<int>(an, options);
Parallel.ForEach(Enumerable.Range(1, 100), (x) => {
actionBlock.Post(x);
});
actionBlock.Complete();
actionBlock.Completion.Wait();
watch.Stop();
Console.WriteLine($"Time take to execute: {watch.ElapsedMilliseconds} ms");
Console.ReadLine();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment