Boradcast Block for Rest Api
Use BroadcastBlock<T> when you want to perform multiple, independent actions on each piece of data that you have. For example, if you have a stream of images and you want to save each image to disk, display it in a UI, and upload it to a cloud server, a BroadcastBlock<T> could handle broadcasting each image to separate operations that handle those actions.
using System.Threading.Tasks.Dataflow;
namespace TplDataFlowDemo.DemoBlocks;
public class DemoBroadCastBlock
{
private readonly BroadcastBlock<string> _broadcast;
private readonly ActionBlock<string> _service1;
private readonly ActionBlock<string> _service2;
public DemoBroadCastBlock()
{
_broadcast = new BroadcastBlock<string>(message => message);
_service1 = new ActionBlock<string>(ProcessService1);
_service2 = new ActionBlock<string>(ProcessService2);
_broadcast.LinkTo(_service1, new DataflowLinkOptions { PropagateCompletion = true });
_broadcast.LinkTo(_service2, new DataflowLinkOptions { PropagateCompletion = true });
}
public async Task StartFlow(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
// Simulate getting a new message, normally this could be from event or queue.
var item = Guid.NewGuid().ToString();
await _broadcast.SendAsync(item);
// Simulate delay between each new item.
await Task.Delay(1000);
}
_broadcast.Complete();
await Task.WhenAll(_service1.Completion, _service2.Completion);
}
private async Task ProcessService1(string item)
{
// Simulate processing delay in Service 1.
await Task.Delay(200);
Console.WriteLine($"Service1: {item}");
}
private async Task ProcessService2(string item)
{
// Simulate processing delay in Service 2.
await Task.Delay(300);
Console.WriteLine($"Service2: {item}");
}
}
// use in console like...
var broadCast = new DemoBroadCastBlock();
await broadCast.StartFlow(CancellationToken.None);
In this example, the BroadcastBlock is linked to two ActionBlock objects. When a number is posted to the BroadcastBlock, both ActionBlock objects receive the message and process it independently.
Files you can download: