Skip to content

Instantly share code, notes, and snippets.

@kadukf
Created August 31, 2018 10:29
Show Gist options
  • Select an option

  • Save kadukf/ddc7bd972bdbb0752b1743ee9291bf66 to your computer and use it in GitHub Desktop.

Select an option

Save kadukf/ddc7bd972bdbb0752b1743ee9291bf66 to your computer and use it in GitHub Desktop.
Tasks paralellization using Semaphore
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);
}
@Tewr
Copy link

Tewr commented Sep 7, 2018

Nice. You should move await semaphore.WaitAsync(); to just before the try block for consistency. WaitAsync should rarely fail in this particular case, but assuming it could, you certainly don't want to call Release, so moving it out would clarify your intent.

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