Skip to content

Instantly share code, notes, and snippets.

@kadukf
Created August 31, 2018 10:27
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 kadukf/4ecafae97d1661413b029eae90a71e46 to your computer and use it in GitHub Desktop.
Save kadukf/4ecafae97d1661413b029eae90a71e46 to your computer and use it in GitHub Desktop.
Tasks paralellization using Enumerable/ConcurrentQueue approach
static async Task<(IReadOnlyCollection<int>, TimeSpan)> RunComputationsAsync(int maxDegreeOfParallelism, int messageCount)
{
ConcurrentQueue<int> input = new ConcurrentQueue<int>(System.Linq.Enumerable.Range(0, messageCount));
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
var tasks = System.Linq.Enumerable.Range(1, maxDegreeOfParallelism).Select(async _ =>
{
List<int> results = new List<int>();
while (input.TryDequeue(out int item))
{
await Task.Delay(item == 3 ? 10000 : 1000);
results.Add(item * 2);
}
return results;
}).ToList();
await Task.WhenAll(tasks);
stopwatch.Stop();
return (tasks.SelectMany(t => t.Result).ToImmutableList(), stopwatch.Elapsed);
}
@ObliviateCharm
Copy link

Hi, can you please explain a little bit how this works, and why are you only running (maxDegreeOfParallelism -1) threads at a time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment