Created
August 31, 2018 10:27
-
-
Save kadukf/4ecafae97d1661413b029eae90a71e46 to your computer and use it in GitHub Desktop.
Tasks paralellization using Enumerable/ConcurrentQueue approach
This file contains 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
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, can you please explain a little bit how this works, and why are you only running (maxDegreeOfParallelism -1) threads at a time.