TransformMany Block


TransformManyBlock is the opposite of the TransformBlock. Its implementation relies on accepting one item and producing many messages in the form of IEnumerable. It takes as a parameter a function that returns an object of type IEnumerable, therefore it uses a lazy evaluation approach. Functions that uses lazy evaluation like "yield return $"{item}" will provide a performance improvement.

Getting results back: Action and LinkTo function for 
To receive from the TransformManyBlocks, we need to initialize an Anction block of the same type and then link these two blocks together with LinkTo functionality.

A TransformManyBlock can produce multiple outputs, or none, for each input. It's designed to be used when an input can result in multiple outputs (like splitting a sentence into words, for example) and you want to process each output separately.

public static async Task DemoBufferTransformManyAction()
{
// initialize buffer
var bufferBlock = new BufferBlock<string>();
// initialize transfer (TransformManyBlock used here)
var transformManyBlock = new TransformManyBlock<string, string>(async sentence =>
{
await Task.Delay(1000); // Simulating some processing time
return sentence.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
});
// initialize action
var actionBlock = new ActionBlock<string>(word =>
{
Console.WriteLine($"Action consumes: {word} sent from transform");
});
// link them
bufferBlock.LinkTo(transformManyBlock);
transformManyBlock.LinkTo(actionBlock);
// action
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"buffer will receive: sentence {i}");
await bufferBlock.SendAsync($"This is sentence {i}"); // Send data to the buffer block
}
bufferBlock.Complete(); // Signal that no more data will be sent
await actionBlock.Completion; // Wait for all processing to complete
}

 


No files yet, migration hasn't completed yet!