- Published on
Mastering Task Parallel Library (TPL) Methods in C#: A Comprehensive Guide
- Authors
- Name
- Mohammed Rabby Hasan
- @rabbyalone
The Task Parallel Library (TPL) in C# is a powerful framework for managing and executing parallel tasks efficiently. It simplifies the development of multi-threaded and concurrent applications. In this article, we'll explore the core TPL methods and provide real-world examples for each one.
Task.Run(Action action)
Task.Run
is a simple way to run a specified action asynchronously on a separate thread.
Example:
Task task = Task.Run(() => Console.WriteLine("Task is running..."));
task.Wait();
Task.Factory.StartNew(Action action)
Task.Factory.StartNew
is similar to Task.Run
and allows you to run an action asynchronously.
Example:
Task task = Task.Factory.StartNew(() => Console.WriteLine("Task is running..."));
task.Wait();
Task.Delay(int milliseconds)
Task.Delay
creates a task that delays execution asynchronously for the specified time.
Example:
async Task DelayExample()
{
Console.WriteLine("Start of DelayExample");
await Task.Delay(2000); // Delay for 2 seconds
Console.WriteLine("After 2 seconds delay");
}
Task.WhenAll(IEnumerable<Task> tasks)
Task.WhenAll
waits for all the provided tasks to complete.
Example:
async Task WhenAllExample()
{
var tasks = new List<Task>
{
Task.Run(() => Console.WriteLine("Task 1")),
Task.Run(() => Console.WriteLine("Task 2")),
Task.Run(() => Console.WriteLine("Task 3"))
};
await Task.WhenAll(tasks);
Console.WriteLine("All tasks completed.");
}
Task.WhenAny(IEnumerable<Task> tasks)
Task.WhenAny
returns the task that completes first.
Example:
async Task WhenAnyExample()
{
var tasks = new List<Task>
{
Task.Delay(2000).ContinueWith(_ => 1),
Task.Delay(1000).ContinueWith(_ => 2),
Task.Delay(3000).ContinueWith(_ => 3)
};
var firstCompletedTask = await Task.WhenAny(tasks);
Console.WriteLine("First task completed with result: " + await firstCompletedTask);
}
Parallel.ForEach(IEnumerable<TSource> source, Action<TSource> body)
Parallel.ForEach
enables parallel processing of a collection.
Example:
var numbers = Enumerable.Range(1, 10);
Parallel.ForEach(numbers, num =>
{
Console.WriteLine($"Processed number {num}");
});
Parallel LINQ (PLINQ)
PLINQ allows parallel processing of data collections using LINQ queries.
Example:
var numbers = Enumerable.Range(1, 1000);
var parallelQuery = numbers.AsParallel().Where(num => num % 2 == 0);
foreach (var num in parallelQuery)
{
Console.WriteLine($"Even number: {num}");
}