TransformBlock
您可以创建一个抽象类型,它实现与目标块类型( implementsIPropagatorBlock
和)相同的接口IReceivableSourceBlock
。
不要复制该块的行为,而是将所有方法调用委托给innerBlock
该类型的一个。
public abstract class AbstractMultiplyBlock<TInput, TOutput>
: IPropagatorBlock<TInput, TOutput>, IReceivableSourceBlock<TOutput>
{
private readonly TransformBlock<TInput, TOutput> innerBlock;
protected AbstractMultiplyBlock(TransformBlock<TInput, TOutput> innerBlock)
{
this.innerBlock = innerBlock;
}
// ... interface implementations omitted for brevity, see appendix
}
这个抽象类具有与该类相同的所有属性和方法TransformBlock
。现在,创建将 的实例传递TransformBlock
给基本构造函数的派生类型。
public sealed class MultiplyByTwoBlock : AbstractMultiplyBlock<int, int>
{
public MultiplyByTwoBlock()
: base(new TransformBlock<int, int>(x => x * 2))
{
}
}
public sealed class MultiplyByThreeBlock : AbstractMultiplyBlock<int, int>
{
public MultiplyByThreeBlock()
: base(new TransformBlock<int, int>(x => x * 3))
{
}
}
用法与任何其他实例相同TransformBlock
var calculator1 = new MultiplyByTwoBlock();
var calculator2 = new MultiplyByThreeBlock();
calculator1.LinkTo(calculator2);
// x = 10 * 2 * 3
calculator1.Post(10);
var x = calculator2.Receive();
附录
完整的源代码AbstractMultiplyBlock
public abstract class AbstractMultiplyBlock<TInput, TOutput>
: IPropagatorBlock<TInput, TOutput>, IReceivableSourceBlock<TOutput>
{
private readonly TransformBlock<TInput, TOutput> innerBlock;
protected AbstractMultiplyBlock(TransformBlock<TInput, TOutput> innerBlock)
{
this.innerBlock = innerBlock;
}
public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source,
bool consumeToAccept)
{
return ((ITargetBlock<TInput>)innerBlock).OfferMessage(messageHeader, messageValue, source, consumeToAccept);
}
public void Complete()
{
innerBlock.Complete();
}
public void Fault(Exception exception)
{
((IDataflowBlock)innerBlock).Fault(exception);
}
public Task Completion
{
get { return innerBlock.Completion; }
}
public IDisposable LinkTo(ITargetBlock<TOutput> target, DataflowLinkOptions linkOptions)
{
return innerBlock.LinkTo(target, linkOptions);
}
public TOutput ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target, out bool messageConsumed)
{
return ((ISourceBlock<TOutput>)innerBlock).ConsumeMessage(messageHeader, target, out messageConsumed);
}
public bool ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
{
return ((ISourceBlock<TOutput>)innerBlock).ReserveMessage(messageHeader, target);
}
public void ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<TOutput> target)
{
((ISourceBlock<TOutput>)innerBlock).ReleaseReservation(messageHeader, target);
}
public bool TryReceive(Predicate<TOutput> filter, out TOutput item)
{
return innerBlock.TryReceive(filter, out item);
}
public bool TryReceiveAll(out IList<TOutput> items)
{
return innerBlock.TryReceiveAll(out items);
}
}