Have you ever heard of ActionBlock in C#?

In C#, ActionBlock<T> is a class from the System.Threading.Tasks.Dataflow namespace, which is part of the Task Parallel Library (TPL) Dataflow library. It is used for creating dataflow pipelines where you can process data asynchronously and in parallel. The ActionBlock<T> is specifically designed to execute a delegate (an action) for each piece of data it receives.

Key Features of ActionBlock<T>

  1. Asynchronous Processing: It processes data asynchronously, making it suitable for I/O-bound or CPU-bound operations.
  2. Bounded Capacity: You can limit the number of items that can be queued in the block.
  3. Parallelism: You can specify the degree of parallelism to control how many items are processed simultaneously.
  4. Thread-Safe: It is thread-safe, so multiple threads can post data to it without additional synchronization.

Basic Usage

Here’s an example of how to use ActionBlock<T>:

using System;
using System.Threading.Tasks;
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 input =>
        {
            // Simulate some work
            await Task.Delay(1000);
            Console.WriteLine($"Processed: {input}");
        }, new ExecutionDataflowBlockOptions
        {
            MaxDegreeOfParallelism = 2 // Process up to 2 items in parallel
        });

        // Post data to the block
        for (int i = 1; i <= 10; i++)
        {
            actionBlock.Post(i);
            Console.WriteLine($"Posted: {i}");
        }

        // Signal that no more data will be posted
        actionBlock.Complete();

        // Wait for the block to process all items
        await actionBlock.Completion;

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

Options for ActionBlock<T>

  • MaxDegreeOfParallelism: Controls how many items can be processed simultaneously.
  • BoundedCapacity: Limits the number of items that can be queued in the block.
  • CancellationToken: Allows cancellation of the block's operations.

var actionBlock = new ActionBlock<int>(async input =>
{
    await Task.Delay(1000);
    Console.WriteLine($"Processed: {input}");
}, new ExecutionDataflowBlockOptions
{
    MaxDegreeOfParallelism = 2,
    BoundedCapacity = 5 // Queue can hold up to 5 items
});

for (int i = 1; i <= 10; i++)
{
    // Post data and wait if the block is full
    await actionBlock.SendAsync(i);
    Console.WriteLine($"Posted: {i}");
}

actionBlock.Complete();
await actionBlock.Completion;        

Use Cases

  • Batch Processing: Process a large number of items in parallel.
  • Pipeline Processing: Use as part of a larger dataflow pipeline with other blocks like TransformBlock or BufferBlock.
  • Asynchronous Workflows: Handle asynchronous tasks efficiently.


Installation

To use ActionBlock<T>, you need to install the System.Threading.Tasks.Dataflow NuGet package:

dotnet add package System.Threading.Tasks.Dataflow        




Julio César

Senior Full Stack Developer | Java | Spring Boot | React | Angular | AWS | APIs

2 周

Love this

回复
Gabriel Levindo

Android Developer | Mobile Software Engineer | Kotlin | Jetpack Compose | XML

2 周

Well done!!

回复
Leo Ely

DevOps Engineer | DevSecOps | GitOps | GitHub Actions | AWS | Java

2 周

Great advice for the increased need of efficiency and performance in applications nowadays!

回复
Alexandre Germano Souza de Andrade

Senior Software Engineer | Backend-Focused Fullstack Developer | .NET | C# | Angular | React.js | TypeScript | JavaScript | Azure | SQL Server

2 周

Nice breakdown Rafael Da Silva, thanks for sharing!

回复
André Ramos

Senior Software Engineer | Fullstack Software Developer | Java | Spring Boot | Micro Services | Angular | AWS | TechLead | Head Solutions

2 周

Very helpful! Thanks for sharing another one! ??

要查看或添加评论,请登录

Rafael Da Silva的更多文章

  • Single Responsability Principal (SRP)

    Single Responsability Principal (SRP)

    A different way of memorizing the SOLID principles First of all, I apologize for any mistakes in English, I'm not a…

    14 条评论
  • Using Docker to Create a Development Environment.

    Using Docker to Create a Development Environment.

    Today, we’ll explore how to set up a development environment using Docker. This post is divided into two parts: in the…

    37 条评论
  • dotnet list

    dotnet list

    Today's tip is about an interesting command. Many may already know it, but in my case, since I usually work with Visual…

    25 条评论