| | | 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 IEnumerableExtensions |
| | | 10 | | { |
| | | 11 | | public static BufferBlock<I> AsSourceBlock<I>(this IEnumerable<I> source) => |
| | 9 | 12 | | AsSourceBlock(source, true); |
| | | 13 | | |
| | | 14 | | public static BufferBlock<I> AsSourceBlock<I>(this IEnumerable<I> source, bool complete) => |
| | 9 | 15 | | source.AsSourceBlock(new DataflowBlockOptions(), complete); |
| | | 16 | | |
| | | 17 | | public static BufferBlock<I> AsSourceBlock<I>( |
| | | 18 | | this IEnumerable<I> source, |
| | | 19 | | DataflowBlockOptions options |
| | 0 | 20 | | ) => AsSourceBlock(source, options, true); |
| | | 21 | | |
| | | 22 | | public static BufferBlock<I> AsSourceBlock<I>( |
| | | 23 | | this IEnumerable<I> source, |
| | | 24 | | DataflowBlockOptions options, |
| | | 25 | | bool complete |
| | | 26 | | ) |
| | | 27 | | { |
| | 9 | 28 | | var bufferBlock = new BufferBlock<I>(options); |
| | 9 | 29 | | _ = source.FeedTo(bufferBlock, complete, options.CancellationToken); |
| | 9 | 30 | | return bufferBlock; |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | public static Task FeedTo<T>( |
| | | 34 | | this IEnumerable<T> source, |
| | | 35 | | ITargetBlock<T> target, |
| | | 36 | | CancellationToken cancel = default |
| | 0 | 37 | | ) => FeedTo(source, target, true, cancel); |
| | | 38 | | |
| | | 39 | | public static async Task FeedTo<T>( |
| | | 40 | | this IEnumerable<T> source, |
| | | 41 | | ITargetBlock<T> target, |
| | | 42 | | bool complete, |
| | | 43 | | CancellationToken cancel = default |
| | | 44 | | ) |
| | | 45 | | { |
| | | 46 | | try |
| | | 47 | | { |
| | 2206270 | 48 | | foreach (var e in source) |
| | | 49 | | { |
| | 1103126 | 50 | | var consumed = await target.SendAsync(e, cancel); |
| | 1103126 | 51 | | if (cancel.IsCancellationRequested) |
| | | 52 | | { |
| | | 53 | | break; |
| | | 54 | | } |
| | | 55 | | |
| | 1103126 | 56 | | if (!consumed) |
| | | 57 | | { |
| | 0 | 58 | | throw new ArgumentException("Target does not accept message"); |
| | | 59 | | } |
| | | 60 | | } |
| | 9 | 61 | | if (complete) |
| | | 62 | | { |
| | 9 | 63 | | target.Complete(); |
| | | 64 | | } |
| | 9 | 65 | | } |
| | 0 | 66 | | catch (Exception e) |
| | | 67 | | { |
| | 0 | 68 | | target.Fault(e); |
| | 0 | 69 | | } |
| | 9 | 70 | | } |
| | | 71 | | } |
| | | 72 | | } |