Action Block


In C#, TPL Dataflow is a library for building concurrent and dataflow-enabled applications. The ActionBlock is one of the core building blocks provided by TPL Dataflow.

An ActionBlock represents a dataflow block that processes data asynchronously and potentially concurrently. It encapsulates an action delegate that is invoked for each data item received by the block. When you post a data item to an ActionBlock, it queues the item for processing by invoking the action delegate asynchronously. ActionBlock manages the concurrency and scheduling of these actions, ensuring that they execute safely and efficiently.

Key features and characteristics of ActionBlock include:

Asynchronous Processing: ActionBlock processes data asynchronously, allowing the calling thread to continue execution without waiting for the action to complete.

Concurrent Execution: ActionBlock can process multiple data items concurrently, depending on the degree of parallelism you specify.

Back Pressure Handling: ActionBlock automatically applies back pressure to its upstream components, meaning it can control the rate at which it accepts new data items. This helps prevent resource exhaustion and ensures smooth operation of the dataflow pipeline.

Completion and Error Handling: ActionBlock handles completion and error conditions gracefully. You can await its completion to know when all data items have been processed, and you can also handle any exceptions thrown during the processing of data items.

Here's a simple example demonstrating the usage of ActionBlock:

using System;
using System.Threading.Tasks.Dataflow;

class Program
{
    static async Task Main(string[] args)
    {
        // Create an ActionBlock that processes integers
        var actionBlock = new ActionBlock<int>(async num =>
        {
            await Task.Delay(100);

                   // Simulate some processing time
            Console.WriteLine($"Processed: {num}");
        });       

             // Post some data to the ActionBlock
        for (int i = 0; i < 10; i++)
        {
            await actionBlock.SendAsync(i);
        }       

             // Signal the completion of data posting
        actionBlock.Complete();       

             // Wait for all data to be processed
        await actionBlock.Completion;       

            Console.WriteLine("All data processed.");
    }
}

In this example, we create an ActionBlock that processes integers asynchronously. We post some data to the block, wait for all data to be processed, and then indicate that no more data will be posted by calling the Complete() method. Finally, we wait for the block to finish processing all remaining items by awaiting Completion.

 


No files yet, migration hasn't completed yet!