BroadcastBlock C# with Example



BroadcastBlock C# with Example

(Copy an item and send the copies to every block that it ’s linked to) 
Unlike BufferBlock, BroadcastBlock ’s mission in life is to enable all targets linked from the block to get a copy of 
every element published, continually overwriting the “current ” value with those propagated to it. 
Additionally, unlike BufferBlock, BroadcastBlock doesn ’t hold on to data unnecessarily. After a particular datum has 
been offered to all targets, that element will be overwritten by whatever piece of data is next in line (as with all 
dataflow blocks, messages are handled in FIFO order). That element will be offered to all targets, and so on. 
 

Asynchronous Producer/Consumer with a Throttled Producer 
var ui = TaskScheduler.FromCurrentSynchronizationContext(); 
var bb = new BroadcastBlock(i => i); 
var saveToDiskBlock = new ActionBlock(item => 
item.Image.Save(item.Path) 
); 
var showInUiBlock = new ActionBlock(item => 
imagePanel.AddImage(item.Image), 
new DataflowBlockOptions { TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext() } 
); 
bb.LinkTo(saveToDiskBlock); 
bb.LinkTo(showInUiBlock); 
Exposing Status from an Agent 
public class MyAgent 
{ 
public ISourceBlock Status { get; private set; } 
public MyAgent() 
{ 
Status = new BroadcastBlock(); 
Run(); 
} 
private void Run() 
{ 
Status.Post("Starting"); 
Status.Post("Doing cool stuff"); 
… 
Status.Post("Done"); 
} 
} 
Introduction to TPL Dataflow by Stephen Toub 

0 Comment's

Comment Form

Submit Comment