var blockOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 1 }; var block = new ActionBlock(async x => { await Task.Delay(TimeSpan.FromSeconds(1)); // simulate some work if (x % 2 == 0) { throw new ArgumentException("even numbers are not allowed"); } }, blockOptions); block.Post(1); block.Post(2); block.Post(3); block.Complete(); try { await block.Completion; } catch (AggregateException ex) { ex.Flatten().Handle(innerEx => { if (innerEx is ArgumentException) { Console.WriteLine($"error: {innerEx.Message}"); return true; } else { return false; } }); }
var blockOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 1 }; var block = new TransformBlockIn this example, we create a TransformBlock that takes an integer as input, doubles it, and checks whether it is odd or even. If it's even, an ArgumentException is thrown and the block is faulted. We then post three numbers (1, 2, and 3) to the block and complete it. When we wait for the block to complete, we catch any exceptions using an AggregateException and inspect each inner exception to see if it's an ArgumentException. If it is, we print out the error message and fault the block. After waiting for any remaining output to become available, we check if the block's completion task is faulted and print out the exception if it is.(async x => { await Task.Delay(TimeSpan.FromSeconds(1)); // simulate some work if (x % 2 == 0) { throw new ArgumentException("even numbers are not allowed"); } return x * 2; }, blockOptions); block.Post(1); block.Post(2); block.Post(3); block.Complete(); try { await block.Completion; } catch (AggregateException ex) { ex.Flatten().Handle(innerEx => { if (innerEx is ArgumentException) { Console.WriteLine($"error: {innerEx.Message}"); block.Fault(innerEx); return true; } else { return false; } }); } while (await block.OutputAvailableAsync()) { Console.WriteLine(block.Receive()); } if (block.Completion.IsFaulted) { Console.WriteLine($"block faulted with {block.Completion.Exception}"); }