| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Threading; |
| | | 4 | | using System.Threading.Tasks; |
| | | 5 | | using System.Threading.Tasks.Dataflow; |
| | | 6 | | |
| | | 7 | | namespace CounterpointCollective.Dataflow |
| | | 8 | | { |
| | | 9 | | public static class IAsyncEnumerableExtensions |
| | | 10 | | { |
| | | 11 | | public static BufferBlock<I> AsSourceBlock<I>(this IAsyncEnumerable<I> source) => |
| | 2056 | 12 | | AsSourceBlock(source, true); |
| | | 13 | | |
| | | 14 | | public static BufferBlock<I> AsSourceBlock<I>( |
| | | 15 | | this IAsyncEnumerable<I> source, |
| | | 16 | | bool complete |
| | 2056 | 17 | | ) => AsSourceBlock(source, new DataflowBlockOptions(), complete); |
| | | 18 | | |
| | | 19 | | public static BufferBlock<I> AsSourceBlock<I>( |
| | | 20 | | this IAsyncEnumerable<I> source, |
| | | 21 | | DataflowBlockOptions options |
| | 0 | 22 | | ) => AsSourceBlock(source, options, true); |
| | | 23 | | |
| | | 24 | | public static BufferBlock<I> AsSourceBlock<I>( |
| | | 25 | | this IAsyncEnumerable<I> source, |
| | | 26 | | DataflowBlockOptions options, |
| | | 27 | | bool complete |
| | | 28 | | ) |
| | | 29 | | { |
| | 2056 | 30 | | var bufferBlock = new BufferBlock<I>(options); |
| | 2056 | 31 | | _ = source.FeedTo(bufferBlock, complete, options.CancellationToken); |
| | 2056 | 32 | | return bufferBlock; |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | public static Task FeedTo<T>( |
| | | 36 | | this IAsyncEnumerable<T> source, |
| | | 37 | | ITargetBlock<T> target, |
| | | 38 | | CancellationToken cancel = default |
| | 0 | 39 | | ) => FeedTo(source, target, true, cancel); |
| | | 40 | | |
| | | 41 | | public static async Task FeedTo<T>( |
| | | 42 | | this IAsyncEnumerable<T> source, |
| | | 43 | | ITargetBlock<T> target, |
| | | 44 | | bool complete, |
| | | 45 | | CancellationToken cancel = default |
| | | 46 | | ) |
| | | 47 | | { |
| | | 48 | | try |
| | | 49 | | { |
| | 266963 | 50 | | await foreach (var e in source.WithCancellation(cancel)) |
| | | 51 | | { |
| | 131426 | 52 | | var consumed = await target.SendAsync(e, cancel); |
| | 131426 | 53 | | if (cancel.IsCancellationRequested) |
| | | 54 | | { |
| | | 55 | | break; |
| | | 56 | | } |
| | | 57 | | |
| | 131426 | 58 | | if (!consumed) |
| | | 59 | | { |
| | 1 | 60 | | throw new ArgumentException("Target does not accept message"); |
| | | 61 | | } |
| | | 62 | | } |
| | 2054 | 63 | | if (complete) |
| | | 64 | | { |
| | 2054 | 65 | | target.Complete(); |
| | | 66 | | } |
| | 2054 | 67 | | } |
| | 2 | 68 | | catch (Exception e) |
| | | 69 | | { |
| | 2 | 70 | | target.Fault(e); |
| | 2 | 71 | | } |
| | 2056 | 72 | | } |
| | | 73 | | } |
| | | 74 | | } |