From 0d7200f30f8c97f90daca456a276a1d1deddb337 Mon Sep 17 00:00:00 2001 From: Jaex Date: Wed, 24 Nov 2021 07:37:17 +0300 Subject: [PATCH] Added ForEachAsync --- ShareX.HelpersLib/Helpers/Helpers.cs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/ShareX.HelpersLib/Helpers/Helpers.cs b/ShareX.HelpersLib/Helpers/Helpers.cs index c3ce79901..66cf125d2 100644 --- a/ShareX.HelpersLib/Helpers/Helpers.cs +++ b/ShareX.HelpersLib/Helpers/Helpers.cs @@ -1665,5 +1665,26 @@ public static string CreateChecksumFile(string filePath) return null; } + + public static Task ForEachAsync(IEnumerable inputEnumerable, Func asyncProcessor, int maxDegreeOfParallelism) + { + SemaphoreSlim throttler = new SemaphoreSlim(maxDegreeOfParallelism, maxDegreeOfParallelism); + + IEnumerable tasks = inputEnumerable.Select(async input => + { + await throttler.WaitAsync(); + + try + { + await asyncProcessor(input); + } + finally + { + throttler.Release(); + } + }); + + return Task.WhenAll(tasks); + } } } \ No newline at end of file