吞下tpl数据流块中抛出的OperationCanceledException

时间:2016-05-13 21:33:32

标签: c# task-parallel-library tpl-dataflow

由于某种原因OperationCanceledExceptionIDataflowBlock抛出,该块不会将此异常传播到其IDataflowBlock.Completion任务。运行下面的代码示例会返回意外的IDataflowBlock.Completion.Status == TaskStatus.RanToCompletion

但是,如果块中抛出的异常类型更改为ArgumentNullException,则IDataflowBlock.Completion.Status将更改为TaskStatus.Faulted,并且异常将保存在其InnerException属性中。

为什么OperationCanceledException被吞噬了?

[TestFixture]
public class TplDataBlockExceptionTest
{
    [Test]
    public void ShouldThrowException()
    {
        // Arrange
        var block = new TransformBlock<int, string>(i =>
        {
            throw new OperationCanceledException();
            return i.ToString();
        });

        // Act

        block.Post(1);
        block.Complete();

        try
        {
            block.Completion.Wait();
        }
        catch (Exception)
        {
            // ignored
        }

        // Assert

        Assert.That(block.Completion.IsFaulted);
    }
}