Created
August 31, 2018 10:29
-
-
Save kadukf/ddc7bd972bdbb0752b1743ee9291bf66 to your computer and use it in GitHub Desktop.
Tasks paralellization using Semaphore
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
| static async Task<(IReadOnlyCollection<int>, TimeSpan)> RunComputationsAsync(int maxDegreeOfParallelism, int messageCount) | |
| { | |
| SemaphoreSlim semaphore = new SemaphoreSlim(maxDegreeOfParallelism); | |
| List<Task<int>> tasks = new List<Task<int>>(); | |
| Stopwatch stopwatch = new Stopwatch(); | |
| stopwatch.Start(); | |
| for (int i = 0; i < messageCount; i++) | |
| { | |
| var item = i; | |
| var task = Task.Run(async () => | |
| { | |
| try | |
| { | |
| await semaphore.WaitAsync(); | |
| await Task.Delay(item == 3 ? 10000 : 1000); | |
| return item * 2; | |
| } | |
| finally | |
| { | |
| semaphore.Release(); | |
| } | |
| }); | |
| tasks.Add(task); | |
| } | |
| await Task.WhenAll(tasks); | |
| stopwatch.Stop(); | |
| return (tasks.Select(t => t.Result).ToImmutableList(), stopwatch.Elapsed); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice. You should move
await semaphore.WaitAsync();to just before the try block for consistency.WaitAsyncshould rarely fail in this particular case, but assuming it could, you certainly don't want to callRelease, so moving it out would clarify your intent.