Skip to content

Instantly share code, notes, and snippets.

@Szer
Created April 11, 2024 10:38
Show Gist options
  • Save Szer/600ab682d343f1e2aef4ef02365d5d63 to your computer and use it in GitHub Desktop.
Save Szer/600ab682d343f1e2aef4ef02365d5d63 to your computer and use it in GitHub Desktop.
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
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