Have you ever heard of ActionBlock in C#?
Rafael Da Silva
.NET Software Engineer | Full Stack Developer | C# | Backend | Azure
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>
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>
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
Installation
To use ActionBlock<T>, you need to install the System.Threading.Tasks.Dataflow NuGet package:
dotnet add package System.Threading.Tasks.Dataflow
Senior Full Stack Developer | Java | Spring Boot | React | Angular | AWS | APIs
2 周Love this
Android Developer | Mobile Software Engineer | Kotlin | Jetpack Compose | XML
2 周Well done!!
DevOps Engineer | DevSecOps | GitOps | GitHub Actions | AWS | Java
2 周Great advice for the increased need of efficiency and performance in applications nowadays!
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!
Senior Software Engineer | Fullstack Software Developer | Java | Spring Boot | Micro Services | Angular | AWS | TechLead | Head Solutions
2 周Very helpful! Thanks for sharing another one! ??