C# Task
last modified October 18, 2026
In this article we show how to use Task for concurrent operations in
C#.
Concurrent programming is used for two kinds of work: I/O-bound and CPU-bound. Requesting data from a network, accessing a database, or reading and writing files are I/O-bound operations; the program mostly waits. CPU-bound operations are computationally expensive, such as mathematical calculations or image processing.
Asynchronous operations suit I/O-bound work: while the program waits, the thread
is released to do something else. Parallel operations suit CPU-bound work: the
computation is spread over several cores. Unlike in some other languages, the
Task type is used for both.
A Task represents an operation that may not have completed yet.
Task<TResult> represents an operation that returns a value when it
completes.
Task Task<TResult>
A task has a Status, for example Running,
RanToCompletion, Faulted, or Canceled.
We normally do not create tasks with new Task(...) and
Start(). Instead we use Task.Run for work that must run
on a thread pool thread, and the async methods of the .NET libraries
for I/O.
.NET contains numerous methods such as StreamReader.ReadLineAsync and
HttpClient.GetAsync that perform I/O without blocking a thread. We use
them with the async and await keywords. Awaiting a task
suspends the current method, not the thread, and resumes it when the task
completes. See the async/await tutorial for
details.
task.Result,
task.Wait(), or Task.WaitAll in code that can use
await. Blocking wastes a thread and can cause deadlocks in
applications with a synchronization context, such as GUI applications.
C# Task.Run
The Task.Run method queues work to run on a thread pool thread and
returns a task that represents it. It is suitable for CPU-bound work and for
moving blocking code off the calling thread.
Console.WriteLine($"Main thread {Environment.CurrentManagedThreadId} begin");
Task task = Task.Run(() =>
{
Console.WriteLine($"Thread {Environment.CurrentManagedThreadId} begin");
Thread.Sleep(2000);
Console.WriteLine($"Thread {Environment.CurrentManagedThreadId} end");
});
Console.WriteLine($"Main thread {Environment.CurrentManagedThreadId} waiting");
await task;
Console.WriteLine($"Main thread {Environment.CurrentManagedThreadId} end");
The main thread starts a task and awaits it. We print the managed thread ids to see where the code runs.
$ dotnet run Main thread 1 begin Main thread 1 waiting Thread 4 begin Thread 4 end Main thread 4 end
The lambda runs on thread 4 of the thread pool. The main thread does not wait;
it continues and prints "waiting". The await releases it, and the
rest of the method resumes later on a thread pool thread, which is why the last
line reports thread 4. In a console application there is no synchronization
context that would bring the code back to the original thread. The thread ids
vary between runs.
C# Task<TResult>
Task<TResult> represents a task that returns a result. The
await operator unwraps the result.
Task<int> task = Task.Run(() =>
{
Thread.Sleep(2000);
return 2 + 3;
});
Console.WriteLine($"completed: {task.IsCompleted}");
int res = await task;
Console.WriteLine($"result: {res}");
Console.WriteLine($"status: {task.Status}");
Task<string> done = Task.FromResult("cached value");
Console.WriteLine(await done);
The program shows how to wait for a task that returns a computation result.
Console.WriteLine($"completed: {task.IsCompleted}");
Right after the start, the task is still running, so this prints
False.
Task<string> done = Task.FromResult("cached value");
Task.FromResult creates a task that is already completed. It is handy
when a method must return a task but the value is available synchronously, for
example from a cache.
$ dotnet run completed: False result: 5 status: RanToCompletion cached value
C# Task.Delay
Task.Delay creates a task that completes after a time delay. It is the
asynchronous counterpart of Thread.Sleep.
Console.WriteLine("step 1");
await DoTask();
Console.WriteLine("step 2");
async Task DoTask()
{
await Task.Delay(2000);
Console.WriteLine("task finished");
}
A method that uses await must be marked with the async
modifier.
await Task.Delay(2000);
Task.Delay creates a task that completes after two seconds. The
await operator suspends the DoTask method until then,
without blocking any thread. The caller awaits DoTask as well, so
"step 2" is printed after the task finishes.
$ dotnet run step 1 task finished step 2
C# async Main method
With top-level statements, we can use await directly; the compiler
generates an async entry point. In a traditional program, the
Main method must be declared as static async Task Main.
await File.WriteAllLinesAsync("words.txt", ["sky", "main", "club", "cotton", "rocket"]);
using StreamReader reader = File.OpenText("words.txt");
string? res = await reader.ReadLineAsync();
Console.WriteLine($"First line is: {res}");
The example writes a small text file and reads its first line asynchronously.
string? res = await reader.ReadLineAsync();
The ReadLineAsync method returns a Task<string?>
that represents an asynchronous read operation. The result contains the next line
from the stream, or null when all the characters have been read.
$ dotnet run First line is: sky
C# Task.WhenAll
The Task.WhenAll method creates a task that completes when all of the
provided tasks have completed. Awaiting it does not block a thread. The blocking
variant is Task.WaitAll.
using System.Diagnostics;
var sw = Stopwatch.StartNew();
await Task.WhenAll(F1(), F2(), F3());
Console.WriteLine($"elapsed: {sw.ElapsedMilliseconds / 100 * 100} ms");
async Task F1()
{
await Task.Delay(1000);
Console.WriteLine("f1 finished");
}
async Task F2()
{
await Task.Delay(2500);
Console.WriteLine("f2 finished");
}
async Task F3()
{
await Task.Delay(500);
Console.WriteLine("f3 finished");
}
We measure the execution time of three asynchronous methods that run concurrently.
await Task.WhenAll(F1(), F2(), F3());
All three methods start immediately, because calling an async method runs it
until its first incomplete await and returns the task. The delays
overlap, so the total time is that of the slowest task, not the sum.
$ dotnet run f3 finished f1 finished f2 finished elapsed: 2500 ms
C# sequential vs. concurrent awaiting
Whether independent operations run one after another or at the same time depends on
when we start them. We can also react to the first task that completes with
Task.WhenAny.
using System.Diagnostics;
// sequential: durations add up
var sw = Stopwatch.StartNew();
await Work(1000);
await Work(1000);
Console.WriteLine($"sequential: {sw.ElapsedMilliseconds / 100 * 100} ms");
// concurrent: start both, then await both
sw.Restart();
Task a = Work(1000);
Task b = Work(1000);
await Task.WhenAll(a, b);
Console.WriteLine($"concurrent: {sw.ElapsedMilliseconds / 100 * 100} ms");
// WhenAny: continue as soon as the first task completes
Task<string> slow = Slow("slow", 2000);
Task<string> fast = Slow("fast", 500);
Task<string> first = await Task.WhenAny(slow, fast);
Console.WriteLine($"first: {await first}");
static Task Work(int ms) => Task.Delay(ms);
static async Task<string> Slow(string name, int ms)
{
await Task.Delay(ms);
return name;
}
The example compares the two approaches.
await Work(1000); await Work(1000);
The second operation starts only after the first one has finished, so the durations add up.
Task a = Work(1000); Task b = Work(1000); await Task.WhenAll(a, b);
We start both operations first and await them together. They overlap.
Task<string> first = await Task.WhenAny(slow, fast);
WhenAny returns the task that completed first. The other task keeps
running; it is not cancelled.
$ dotnet run sequential: 2000 ms concurrent: 1000 ms first: fast
C# Task.WhenEach and Parallel.ForEachAsync
.NET 9 added Task.WhenEach, which yields tasks in the order in which
they complete. For running an asynchronous body over a collection with a limit on
the concurrency, there is Parallel.ForEachAsync.
var tasks = new[] { Delay("a", 1500), Delay("b", 500), Delay("c", 1000) };
// results in the order of completion (.NET 9+)
await foreach (var t in Task.WhenEach(tasks))
{
Console.WriteLine(await t);
}
int[] ids = [1, 2, 3, 4, 5, 6];
await Parallel.ForEachAsync(ids, new ParallelOptions { MaxDegreeOfParallelism = 3 },
async (id, ct) =>
{
await Task.Delay(300, ct);
Console.WriteLine($"processed {id}");
});
static async Task<string> Delay(string name, int ms)
{
await Task.Delay(ms);
return name;
}
The first loop prints the results as they become available, b, c, and then a, regardless of their position in the array.
await Parallel.ForEachAsync(ids, new ParallelOptions { MaxDegreeOfParallelism = 3 },
async (id, ct) => { ... });
At most three items are processed at the same time. The body receives a cancellation token.
$ dotnet run b c a processed 1 processed 3 processed 2 processed 6 processed 5 processed 4
The order of the "processed" lines is not deterministic.
C# Task.ContinueWith
The ContinueWith method creates a continuation that runs when the
antecedent task completes. It is the older, callback-style way of chaining tasks.
Today, async/await is preferred; it is easier to read and
handles exceptions and the execution context correctly.
Task<int> task = Task.Run(RunTask).ContinueWith(t => t.Result * 2);
Console.WriteLine(await task);
// the same with async/await
Console.WriteLine(await Chained());
int RunTask()
{
Thread.Sleep(500);
return 1 + 2 + 3;
}
async Task<int> Chained()
{
int value = await Task.Run(RunTask);
return value * 2;
}
In the example, we chain an operation to a task, first with
ContinueWith and then with await. Both print 12.
Task<int> task = Task.Run(RunTask).ContinueWith(t => t.Result * 2);
Inside the continuation, t.Result does not block, because the
antecedent task is already complete. If it had failed, accessing
Result would throw. This is one of the reasons why
ContinueWith is easy to get wrong.
$ dotnet run 12 12
C# Task exceptions
An exception thrown inside a task is stored in the task, which becomes
Faulted. It is rethrown when we await the task.
var task = Task.Run(() =>
{
throw new InvalidOperationException("something failed");
});
try
{
await task;
}
catch (InvalidOperationException e)
{
Console.WriteLine($"caught: {e.Message}");
}
Console.WriteLine(task.Status);
Console.WriteLine(task.Exception?.GetType().Name);
// Wait() wraps the exception in an AggregateException
try
{
task.Wait();
}
catch (AggregateException e)
{
Console.WriteLine($"aggregate: {e.InnerException?.Message}");
}
// with WhenAll only the first exception is rethrown by await; all are in the task
var t1 = Task.Run(() => throw new Exception("one"));
var t2 = Task.Run(() => throw new Exception("two"));
var all = Task.WhenAll(t1, t2);
try
{
await all;
}
catch (Exception e)
{
Console.WriteLine($"await threw: {e.Message}");
Console.WriteLine($"all errors: {string.Join(", ", all.Exception!.InnerExceptions.Select(x => x.Message).Order())}");
}
We observe how failures are reported.
await task;
await rethrows the original exception, so we can catch the specific
type. The task's Exception property always holds an
AggregateException.
task.Wait();
The blocking Wait method (and Result) wraps the exception
in an AggregateException.
var all = Task.WhenAll(t1, t2);
When several tasks fail, await rethrows only the first exception.
All of them are available in all.Exception.InnerExceptions.
$ dotnet run caught: something failed Faulted AggregateException aggregate: something failed await threw: one all errors: one, two
A faulted task whose exception is never observed is silently ignored, so always await your tasks.
C# Task cancellation
Tasks are cancelled cooperatively with a CancellationToken. The
caller signals cancellation through a CancellationTokenSource, and the
task checks the token or passes it to the operations it calls.
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(700));
try
{
await Count(cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("operation was canceled");
}
static async Task Count(CancellationToken token)
{
for (int i = 1; i <= 10; i++)
{
token.ThrowIfCancellationRequested();
Console.WriteLine(i);
await Task.Delay(200, token);
}
}
The source cancels itself after 700 milliseconds.
token.ThrowIfCancellationRequested(); Console.WriteLine(i); await Task.Delay(200, token);
The loop checks the token on each iteration. Task.Delay also accepts
a token and throws a TaskCanceledException, a subclass of
OperationCanceledException, as soon as the token is signalled.
$ dotnet run 1 2 3 4 operation was canceled
C# multiple async requests
The HttpClient class sends HTTP requests and receives responses. With
tasks, we can send many requests concurrently.
// the first example sends real HTTP requests
var urls = new[]
{
"https://example.com", "https://httpbin.org/status/200",
"https://httpbin.org/status/404", "https://httpbin.org/status/500"
};
using var client = new HttpClient();
var tasks = urls.Select(url => client.GetAsync(url)).ToList();
HttpResponseMessage[] responses = await Task.WhenAll(tasks);
for (int i = 0; i < urls.Length; i++)
{
Console.WriteLine($"{urls[i],-35} {(int)responses[i].StatusCode} {responses[i].StatusCode}");
}
We send asynchronous GET requests to several URLs and print the status codes.
var tasks = urls.Select(url => client.GetAsync(url)).ToList();
The GetAsync method sends a GET request and returns a task. Calling it
for every URL starts all the requests; the ToList call makes sure the
query is evaluated now, so that all the requests are in flight at once.
HttpResponseMessage[] responses = await Task.WhenAll(tasks);
We wait for all the responses asynchronously. WhenAll returns an array
of the results in the original order. Note that HTTP error codes such as 404 do not
cause an exception; only network failures do, unless we call
EnsureSuccessStatusCode.
$ dotnet run https://example.com 200 OK https://httpbin.org/status/200 200 OK https://httpbin.org/status/404 404 NotFound https://httpbin.org/status/500 500 InternalServerError
Source
In this article we have used Task for concurrent operations in C#.
Author
List all C# tutorials.