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.Channelspackage (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");
}
}
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
async/await: The compiler turns an async method into a state machine. Eachawaitsuspends 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.Task.WhenAll: Completes when every input task completes and collects all results. If any task throws,WhenAllre-throws the first exception — the others still run to completion.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.CancellationTokenSource: Produces tokens that flow through the async call chain.Cancel()signals;CancelAfterschedules. Downstream code cooperates by callingThrowIfCancellationRequested()or passing the token to async calls that honor it.System.Threading.Channels: A thread-safe async queue.WriteAsyncsuspends when a bounded channel is full (backpressure);ReadAllAsyncreturns anIAsyncEnumerablethat yields items as they arrive and ends when the writer callsComplete().Parallel.ForEachAsync: Added in .NET 6 — runs an async delegate per item withMaxDegreeOfParallelismthrottling. Prefer it over hand-rolledSemaphoreSlimloops 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/awaitover.Resultand.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
CancellationTokenthrough the call chain: Every async method should accept and propagate a token; check it withThrowIfCancellationRequested()inside loops. - Use
Task.Runonly for CPU-bound work: I/O-bound async methods already release the thread — wrapping them inTask.Runjust adds a useless hop. - Prefer
Task.WhenAllover sequential awaits:await task1; await task2;runs one at a time;WhenAlloverlaps them. - Reuse
HttpClient: One shared instance (orIHttpClientFactoryin ASP.NET) — a newHttpClientper call exhausts sockets under load. - Use
SemaphoreSlimfor async rate limiting:WaitAsyncdoesn’t block a thread the way the syncSemaphoredoes.
Common Mistakes
- Using
.Resultor.Wait(): Blocks the thread and can deadlock. Alwaysawait. - 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. Useasync Task—async voidis for event handlers only. - Forgetting
Writer.Complete()on channels:ReadAllAsyncwaits forever for items that will never come. - Abandoning tasks after
WhenAny: The loser keeps running; if it faults unobserved you get a delayedTaskScheduler.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 useIHttpClientFactory.
Further Reading
- Microsoft — Asynchronous programming with async and await — the official tour of the task-based model
- Stephen Cleary — Async and Await best practices — the canonical “don’t block on async” reference
- Microsoft — System.Threading.Channels — bounded/unbounded channel patterns for producer-consumer pipelines
- Companion code examples — runnable C# pipeline samples in the companion repository
Frequently Asked Questions
What's the difference between Task and Task<T>?
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.
Related Resources
Compose Asynchronous Pipelines with Java CompletableFuture
Build non-blocking async pipelines in Java using CompletableFuture with thenCompose, thenCombine, allOf, anyOf, exception handling, timeouts, and custom thread pools.
RecipeConcurrent Async Tasks with asyncio.gather and Task Groups
Compare asyncio.gather and TaskGroup in Python. Handle failures, cancellation, timeouts, concurrency limits, and results as tasks finish.
GuideConcurrency Patterns Guide
Production-ready concurrency patterns: thread pools, async/await, producer-consumer, semaphores, actors, circuit breakers in Python, Java, JS, Go, Elixir.
RecipeScale Concurrent Applications with Java Virtual Threads
Scale Java applications with virtual threads from Project Loom: Thread.ofVirtual, per-task executor, structured concurrency on JDK 25, and scoped values.
RecipeBuild Async Systems with Rust Tokio Runtime
Build async systems in Rust using the Tokio runtime with tasks, channels, select, synchronization primitives, graceful shutdown, and structured concurrency patterns.
RecipeConcurrent Patterns with Go Goroutines and Channels
Build concurrent systems in Go using goroutines, channels, select statements, worker pools, fan-out/fan-in, pipelines, context cancellation, and rate limiting with tickers.