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