C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Task Parallel Library

C# Task Parallel Library

The Task Parallel Library (TPL) provides high-level tools for parallelism and concurrency beyond simple async/await.

1 - Parallel.For and Parallel.ForEach

// CPU-bound parallel work
Parallel.For(0, 10, i =>
{
    Console.WriteLine($"Processing item {i} on thread {Thread.CurrentThread.ManagedThreadId}");
});

var files = Directory.GetFiles("images", "*.png");
Parallel.ForEach(files, file =>
{
    // Resize each image in parallel
    ProcessImage(file);
});

2 - Task.Run for CPU-bound Work

public static async Task<int> HeavyComputationAsync(int input)
{
    // Offload CPU work to a thread pool thread
    return await Task.Run(() =>
    {
        int result = 0;
        for (int i = 0; i < input; i++) result += i;
        return result;
    });
}

int sum = await HeavyComputationAsync(1_000_000);
Console.WriteLine(sum);

3 - async Streams (C# 8+)

public static async IAsyncEnumerable<int> GenerateAsync()
{
    for (int i = 0; i < 10; i++)
    {
        await Task.Delay(100); // simulate async source
        yield return i;
    }
}

await foreach (int value in GenerateAsync())
    Console.WriteLine(value);

Note: Use async/await for I/O-bound work (HTTP calls, file reads, DB queries) and Task.Run() / Parallel for CPU-bound work (image processing, mathematical computation). Mixing these up leads to wasted threads and poor performance.

-Tip-

C# {"id":48,"topic_id":3,"name":"C# Async Programming","slug":"c-async-programming","image":null,"description":"<p>Write non-blocking code with async\/await, Task, and the Task Parallel Library.<\/p>","icon":null,"class":null,"color":null,"status":0,"order":17,"created_at":"2026-05-03T02:03:02.000000Z","updated_at":"2026-05-03T02:03:02.000000Z"} - List of Contents

Related Tutorials: