-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAsyncEnumerableExample.cs
More file actions
78 lines (65 loc) · 2.46 KB
/
Copy pathAsyncEnumerableExample.cs
File metadata and controls
78 lines (65 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using EnumerableAsyncProcessor.Extensions;
namespace EnumerableAsyncProcessor.Example;
public static class AsyncEnumerableExample
{
public static async Task RunExamples()
{
Console.WriteLine("=== IAsyncEnumerable Parallel Processing Examples ===\n");
// Example 1: ForEachAsync with parallel processing
Console.WriteLine("Example 1: Processing async enumerable items in parallel");
var items = GenerateAsyncNumbers(10);
await items
.ForEachAsync(async number =>
{
await Task.Delay(100); // Simulate I/O work
Console.WriteLine($"Processed {number} on thread {Thread.CurrentThread.ManagedThreadId}");
})
.ProcessInParallel(3)
.ExecuteAsync(); // Process with max 3 concurrent tasks
Console.WriteLine("\nExample 2: SelectAsync with transformation");
var transformedItems = GenerateAsyncNumbers(5);
var results = await transformedItems
.SelectAsync(async number =>
{
await Task.Delay(50);
return number * 2;
})
.ProcessInParallel(2)
.ExecuteAsync()
.ToListAsync();
Console.WriteLine($"Transformed results: {string.Join(", ", results)}");
// Example 3: High concurrency for I/O-bound operations
Console.WriteLine("\nExample 3: High concurrency I/O operations");
var ioItems = GenerateAsyncNumbers(20);
await ioItems
.ForEachAsync(async number =>
{
await SimulateApiCall(number);
Console.WriteLine($"API call {number} completed");
})
.ProcessInParallelForIO(10)
.ExecuteAsync(); // Optimized for I/O with high concurrency
Console.WriteLine("\nAll examples completed!");
}
private static async IAsyncEnumerable<int> GenerateAsyncNumbers(int count)
{
for (int i = 1; i <= count; i++)
{
await Task.Yield(); // Simulate async generation
yield return i;
}
}
private static async Task SimulateApiCall(int id)
{
await Task.Delay(Random.Shared.Next(10, 50));
}
private static async Task<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> source)
{
var list = new List<T>();
await foreach (var item in source)
{
list.Add(item);
}
return list;
}
}