简体   繁体   中英

TPL Dataflow: Cancellations

In a long list of IDataflowBlock 's in the .Net library, if I want to limit the execution of the entire collection of blocks to a TimeSpan (say, 5 seconds), does it suffice if I pass a single CancellationToken in the last block's constructor (through DataflowBlockOptions of course) ?

I think the question stands on its own, but for a bit of context, an example:

var token = new CancellationToken(5000);
var options = new DataflowBlockOptions{ CancellationToken = token };

// DataflowBlockOptions not used although possible through overloading
var block1 = new Bufferblock<int>(/*options*/);

// DataflowBlockOptions not used although possible through overloading
var block2 = new TransformBlock<int,int>(i => i + 1/*, options*/);

// Options used here to limit total time to 5 seconds.
var block3 = new ActionBlock<int>(i => Console.WriteLine(i), options);

block1.LinkTo(block2);
block2.LinkTo(block3);

block1.Post(...)

await block3.Completion;

Another way to ask the question: Is there a any benefit here to uncomment the /* options */ in the above snip.

If you want all your Dataflow blocks to fault, then you should pass CancellationToken as an option to each. Alternatively, you could pass it as an option to the first one, and propagate your completion in LinkTo . I don't normally cancel my meshes, but that's my preferred approach to shutting down pipeline-style meshes in general: link with completion and then just complete the first one.

If you don't, then you'll end up with two live blocks connected to a completed block, so any items added to the mesh will flow through and end up in an output buffer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM