StackPractices
intermediate By Mathias Paulenko

Build Async Pipelines with C# async/await and Task.Run

Build async pipelines in C# using async/await, Task.Run, Task.WhenAll, Task.WhenAny, CancellationTokenSource, Channels, and Parallel.ForEachAsync for concurrent I/O and CPU work.

Overview

C#‘s async/await compiles async methods into a state machine — at each await the method suspends and hands the thread back, then resumes when the awaited task finishes. Task and Task<T> are the handles that let you compose those operations: run them in parallel, race them, cancel them, or chain them into pipelines.

This recipe covers the pieces you’ll actually use to build concurrent pipelines: Task.WhenAll for fan-out, Task.WhenAny for first-result-wins, CancellationTokenSource for cooperative cancellation, System.Threading.Channels for producer-consumer work, and Parallel.ForEachAsync/SemaphoreSlim for bounded parallelism. Every example runs on .NET 8+.

When to Use This

  • Async I/O operations (HTTP calls, database queries, file I/O) that can overlap
  • Concurrent API calls whose results you aggregate
  • Long-running operations that need cooperative cancellation
  • Producer-consumer pipelines with backpressure via bounded channels

When not to reach for it: trivially sequential code doesn’t benefit — async adds state-machine overhead. Small CPU-bound loops are faster as plain synchronous code than wrapped in Task.Run. And Task.Run does nothing for I/O-bound work, which already releases the thread while waiting.

Prerequisites

  • .NET 8+
  • System.Threading.Channels package (included in .NET 8+)

Solution

1. Basic async/await

using System.Diagnostics;

public class BasicAsync
{
    // Reuse HttpClient — a new instance per call exhausts sockets.
    // In ASP.NET apps, get instances from IHttpClientFactory instead.
    private static readonly HttpClient client = new();

    public static async Task<string> FetchDataAsync(string url)
    {
        return await client.GetStringAsync(url);
    }

    public static async Task RunAsync()
    {
        var sw = Stopwatch.StartNew();

        // Sequential — 2s total
        var data1 = await FetchDataAsync("https://httpbin.org/delay/1");
        var data2 = await FetchDataAsync("https://httpbin.org/delay/1");

        sw.Stop();
        Console.WriteLine($"Sequential: {sw.ElapsedMilliseconds}ms");
    }
}

2. Task.WhenAll — Parallel Execution

using System.Diagnostics;

public class ParallelAsync
{
    private static readonly HttpClient client = new();

    public static async Task<string> FetchDataAsync(string url)
    {
        return await client.GetStringAsync(url);
    }

    public static async Task RunWhenAllAsync()
    {
        var sw = Stopwatch.StartNew();

        var urls = new[]
        {
            "https://httpbin.org/delay/1",
            "https://httpbin.org/delay/1",
            "https://httpbin.org/delay/1",
            "https://httpbin.org/delay/1",
            "https://httpbin.org/delay/1"
        };

        // Parallel — ~1s total instead of 5s
        var tasks = urls.Select(FetchDataAsync);
        var results = await Task.WhenAll(tasks);

        sw.Stop();
        Console.WriteLine($"Parallel: {sw.ElapsedMilliseconds}ms");
        Console.WriteLine($"Fetched {results.Length} responses");
    }
}

3. Task.WhenAny — First to Complete

Use WhenAny to race a fetch against a timeout. Cancel the loser so it doesn’t run on unobserved — an abandoned task that later faults can surface as an unobserved exception.

public class FirstResultAsync
{
    private static readonly HttpClient client = new();

    public static async Task<string> FetchWithTimeoutAsync(string url, TimeSpan timeout)
    {
        using var cts = new CancellationTokenSource();
        var fetchTask = client.GetStringAsync(url, cts.Token);
        var timeoutTask = Task.Delay(timeout, cts.Token);

        // Returns when either completes
        var completedTask = await Task.WhenAny(fetchTask, timeoutTask);

        if (completedTask == timeoutTask)
        {
            cts.Cancel(); // Abandon the fetch politely
            throw new TimeoutException($"Request to {url} timed out after {timeout}");
        }

        cts.Cancel(); // Cancel the pending timeout
        return await fetchTask;
    }

    public static async Task RunWhenAnyAsync()
    {
        try
        {
            var result = await FetchWithTimeoutAsync(
                "https://httpbin.org/delay/5",
                TimeSpan.FromSeconds(2)
            );
            Console.WriteLine(result);
        }
        catch (TimeoutException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

4. CancellationToken — Cooperative Cancellation

using System.Threading;

public class CancellationAsync
{
    public static async Task ProcessWithCancellationAsync(
        CancellationToken cancellationToken)
    {
        for (int i = 0; i < 100; i++)
        {
            cancellationToken.ThrowIfCancellationRequested();

            await Task.Delay(100, cancellationToken);
            Console.WriteLine($"Processing item {i}");
        }
    }

    public static async Task RunCancellationAsync()
    {
        using var cts = new CancellationTokenSource();

        // Cancel after 500ms
        cts.CancelAfter(TimeSpan.FromMilliseconds(500));

        try
        {
            await ProcessWithCancellationAsync(cts.Token);
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Operation was cancelled");
        }
    }
}

5. Task.Run for CPU-Bound Work

public class CpuBoundAsync
{
    public static long ComputeSum(long start, long end)
    {
        long sum = 0;
        for (long i = start; i < end; i++)
        {
            sum += i;
        }
        return sum;
    }

    public static async Task RunCpuBoundAsync()
    {
        var sw = Stopwatch.StartNew();

        // Run CPU-bound work on the thread pool — don't block the async state machine
        var task1 = Task.Run(() => ComputeSum(0, 50_000_000));
        var task2 = Task.Run(() => ComputeSum(50_000_000, 100_000_000));

        var results = await Task.WhenAll(task1, task2);

        sw.Stop();
        Console.WriteLine($"Sum: {results[0] + results[1]}");
        Console.WriteLine($"Time: {sw.ElapsedMilliseconds}ms");
    }
}

6. System.Threading.Channels — Producer-Consumer

using System.Threading.Channels;

public class ChannelExample
{
    public static async Task RunChannelAsync()
    {
        // Bounded channel with capacity 10 — the producer waits when full (backpressure)
        var channel = Channel.CreateBounded<int>(10);

        // Producer
        async Task ProduceAsync()
        {
            for (int i = 0; i < 100; i++)
            {
                await channel.Writer.WriteAsync(i);
                Console.WriteLine($"Produced: {i}");
            }
            channel.Writer.Complete();
        }

        // Consumer
        async Task ConsumeAsync(int workerId)
        {
            await foreach (var item in channel.Reader.ReadAllAsync())
            {
                await Task.Delay(50); // Simulate processing
                Console.WriteLine($"Worker {workerId} consumed: {item}");
            }
        }

        // Start 3 consumers and 1 producer
        var consumers = Enumerable.Range(0, 3)
            .Select(id => ConsumeAsync(id));
        var producer = ProduceAsync();

        await Task.WhenAll(
            Task.WhenAll(consumers),
            producer
        );

        Console.WriteLine("Channel processing complete");
    }
}
Producer-consumer pipeline — one producer writes items into a bounded channel and three consumer workers read from it concurrently.

7. Parallel.ForEachAsync — Bounded Parallel I/O

public class ParallelForEachAsync
{
    private static readonly HttpClient client = new();

    public static async Task RunParallelForEachAsync()
    {
        var urls = Enumerable.Range(1, 20)
            .Select(i => $"https://httpbin.org/delay/1?page={i}")
            .ToList();

        var options = new ParallelOptions
        {
            MaxDegreeOfParallelism = 5 // Max 5 concurrent
        };

        int successCount = 0;

        await Parallel.ForEachAsync(urls, options, async (url, ct) =>
        {
            try
            {
                var response = await client.GetStringAsync(url, ct);
                Interlocked.Increment(ref successCount);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed {url}: {ex.Message}");
            }
        });

        Console.WriteLine($"Successfully fetched {successCount}/{urls.Count}");
    }
}

8. SemaphoreSlim — Async Rate Limiting

public class SemaphoreAsync
{
    private static readonly HttpClient client = new();

    public static async Task RunSemaphoreAsync()
    {
        var urls = Enumerable.Range(1, 50)
            .Select(i => $"https://httpbin.org/delay/1?id={i}")
            .ToList();

        using var semaphore = new SemaphoreSlim(5); // Max 5 concurrent
        var sw = Stopwatch.StartNew();

        var tasks = urls.Select(async url =>
        {
            await semaphore.WaitAsync();
            try
            {
                var response = await client.GetStringAsync(url);
                return response.Length;
            }
            finally
            {
                semaphore.Release();
            }
        });

        var results = await Task.WhenAll(tasks);

        sw.Stop();
        Console.WriteLine($"Fetched {results.Length} URLs in {sw.ElapsedMilliseconds}ms");
    }
}

9. IAsyncEnumerable — Async Streams

public class AsyncStreamExample
{
    public static async IAsyncEnumerable<int> GenerateNumbersAsync(
        int count,
        [System.Runtime.CompilerServices.EnumeratorCancellation]
        CancellationToken cancellationToken = default)
    {
        for (int i = 0; i < count; i++)
        {
            cancellationToken.ThrowIfCancellationRequested();
            await Task.Delay(100, cancellationToken);
            yield return i;
        }
    }

    public static async Task RunAsyncStreamAsync()
    {
        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));

        try
        {
            await foreach (var num in GenerateNumbersAsync(100, cts.Token))
            {
                Console.WriteLine($"Received: {num}");
            }
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Stream cancelled");
        }
    }
}

How It Works

  1. async/await: The compiler turns an async method into a state machine. Each await suspends the method and returns control to the caller; the continuation resumes on a thread pool thread (or the captured synchronization context) when the task completes.
  2. Task.WhenAll: Completes when every input task completes and collects all results. If any task throws, WhenAll re-throws the first exception — the others still run to completion.
  3. Task.WhenAny: Returns the first task to finish, whatever its outcome. Great for timeouts and racing redundant sources — just remember to cancel or observe the losers.
  4. CancellationTokenSource: Produces tokens that flow through the async call chain. Cancel() signals; CancelAfter schedules. Downstream code cooperates by calling ThrowIfCancellationRequested() or passing the token to async calls that honor it.
  5. System.Threading.Channels: A thread-safe async queue. WriteAsync suspends when a bounded channel is full (backpressure); ReadAllAsync returns an IAsyncEnumerable that yields items as they arrive and ends when the writer calls Complete().
  6. Parallel.ForEachAsync: Added in .NET 6 — runs an async delegate per item with MaxDegreeOfParallelism throttling. Prefer it over hand-rolled SemaphoreSlim loops when you just need “N at a time”.

Variants

TaskCompletionSource — Bridge Callbacks to Tasks

public static Task<string> FromEventAsync()
{
    var tcs = new TaskCompletionSource<string>();

    // Some event-based API
    var timer = new System.Timers.Timer(1000);
    timer.Elapsed += (s, e) =>
    {
        timer.Dispose();
        tcs.SetResult("Timer fired");
    };
    timer.Start();

    return tcs.Task;
}

// Usage
var result = await FromEventAsync();

ConfigureAwait(false)

// In library code, use ConfigureAwait(false) to avoid
// capturing the synchronization context — improves performance
// and prevents deadlocks in UI apps

public static async Task<string> FetchAsync(string url)
{
    // Demo only — in production share a static HttpClient or use IHttpClientFactory
    using var client = new HttpClient();
    var response = await client.GetAsync(url).ConfigureAwait(false);
    return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}

Async Lazy Initialization

public class AsyncLazy<T>
{
    private readonly Lazy<Task<T>> _lazy;

    public AsyncLazy(Func<Task<T>> factory)
    {
        _lazy = new Lazy<Task<T>>(() => Task.Run(factory));
    }

    public Task<T> Value => _lazy.Value;
}

// Usage
var lazyConfig = new AsyncLazy<string>(LoadConfigAsync);
var config = await lazyConfig.Value; // Loads once, caches result

Best Practices

  • Use async/await over .Result and .Wait(): Blocking on async code can deadlock, especially with a synchronization context (ASP.NET classic, WPF, WinForms).
  • Use ConfigureAwait(false) in library code: Avoids capturing the synchronization context — better performance, fewer deadlock paths.
  • Pass CancellationToken through the call chain: Every async method should accept and propagate a token; check it with ThrowIfCancellationRequested() inside loops.
  • Use Task.Run only for CPU-bound work: I/O-bound async methods already release the thread — wrapping them in Task.Run just adds a useless hop.
  • Prefer Task.WhenAll over sequential awaits: await task1; await task2; runs one at a time; WhenAll overlaps them.
  • Reuse HttpClient: One shared instance (or IHttpClientFactory in ASP.NET) — a new HttpClient per call exhausts sockets under load.
  • Use SemaphoreSlim for async rate limiting: WaitAsync doesn’t block a thread the way the sync Semaphore does.

Common Mistakes

  • Using .Result or .Wait(): Blocks the thread and can deadlock. Always await.
  • Missing ConfigureAwait(false) in libraries: Captures the context needlessly — perf hit plus deadlock risk.
  • Not propagating CancellationToken: Accepting a token but never passing it downstream means cancellation silently does nothing.
  • Using async void: Can’t be awaited; exceptions crash the process. Use async Task — async void is for event handlers only.
  • Forgetting Writer.Complete() on channels: ReadAllAsync waits forever for items that will never come.
  • Abandoning tasks after WhenAny: The loser keeps running; if it faults unobserved you get a delayed TaskScheduler.UnobservedTaskException. Cancel or observe it.
  • new HttpClient() per request: Each instance holds its own connection pool — under load this exhausts ephemeral ports. Share the instance or use IHttpClientFactory.

Further Reading

Frequently Asked Questions

What's the difference between Task and Task&lt;T&gt;?

Task is an async operation with no return value (like void); Task<T> returns a value of type T. Await either one — the T just gives you a result to unwrap.

Should I use Task.Run for async I/O methods?

No. I/O-bound async methods already release the thread while waiting — Task.Run only adds a pointless thread-pool hop. Reserve it for CPU-bound work that would otherwise block the caller.

What does ConfigureAwait(false) actually do?

It tells the continuation not to resume on the captured synchronization context. In library code this avoids deadlocks (your caller's Wait()/Result won't need the context you captured) and skips an unnecessary marshal back to a UI or request context.

When should I prefer channels over BlockingCollection?

Almost always in async code. BlockingCollection blocks threads on every wait; Channels uses WriteAsync/ReadAllAsync so waits don't hold a thread. Bounded channels also give you backpressure for free.

Why is async void dangerous?

Nothing can await it, exceptions bypass normal handling and crash the process, and callers can't observe completion. The only legitimate use is event handlers whose signature demands void.

How do I stop Task.WhenAll from overloading a downstream API?

Bound the fan-out. Parallel.ForEachAsync with MaxDegreeOfParallelism, a SemaphoreSlim around each call, or a bounded channel — all cap concurrency at a number the downstream can survive.