Created
April 11, 2024 10:38
-
-
Save Szer/600ab682d343f1e2aef4ef02365d5d63 to your computer and use it in GitHub Desktop.
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
started 1 | |
Finished 1 | |
started 2 | |
Finished 2 | |
started 3 | |
started 4 | |
Finished 3 | |
Finished 4 | |
started 5 | |
Finished 5 | |
started 6 | |
Finished 6 | |
started 7 | |
Finished 7 | |
started 8 | |
Finished 8 | |
started 9 | |
Finished 9 | |
started 10 | |
Finished 10 |
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
using System; | |
using System.Threading.Tasks; | |
using System.Collections.Generic; | |
using System.Linq; | |
var tasks = | |
Enumerable.Range(1,10) | |
.ToAsyncEnum() | |
.SelectAsync(async x => { | |
Console.WriteLine($"started {x}"); | |
await Task.Delay(1000); | |
return x; | |
}); | |
await Parallel.ForEachAsync( | |
tasks, | |
new ParallelOptions { MaxDegreeOfParallelism = 5 }, | |
(x, _) => | |
{ | |
Console.WriteLine($"Finished {x}"); | |
return ValueTask.CompletedTask; | |
}); | |
static class Ext { | |
public static async IAsyncEnumerable<T> ToAsyncEnum<T>(this IEnumerable<T> e) { | |
foreach (var item in e) | |
{ | |
yield return item; | |
} | |
} | |
public static async IAsyncEnumerable<U> SelectAsync<T, U>(this IAsyncEnumerable<T> source, Func<T, Task<U>> f) | |
{ | |
await foreach (var item in source) | |
{ | |
yield return await f(item); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment