Async and await: how Task really works
Course contents (16 lessons)
- The type system
- Records, structs and value equality
- Interfaces and abstract classes
- Generics and constraints
- Delegates, events and lambdas
- Querying and matching data
- LINQ in depth: deferred execution, grouping and joins
- IEnumerable versus IQueryable
- Pattern matching in modern C#
- Async and await: how Task really works
- Async patterns: cancellation, timeouts and async streams
- Application structure
- Dependency injection and service lifetimes
- Configuration, options and logging
- Data and web
- Entity Framework Core basics: DbContext, migrations and queries
- Building a minimal API with ASP.NET Core
- Unit testing with xunit
- Performance and the final project
- Performance basics: Span of T and fewer allocations
- Final project: a notes API with EF Core, DI and logging
The problem async solves
Most programs spend a lot of time waiting: for a database, a web service, a disk. If a thread sits and waits, it cannot do anything else. On a web server, each blocked thread is a request that is held up, and threads are a limited resource. Asynchronous code lets a method say "I will wait for this, and meanwhile the thread can do other work."
The important idea is that async is not about creating more threads. It is about not holding a thread while you wait. Many beginners think await moves work to a background thread. It does not. For I/O such as a network call, no thread is occupied at all while the operating system waits for the answer.
Task and await
A Task represents work that will finish later. Task<T> is the same with a result. An async method returns one of them. Inside, await pauses the method until the awaited task is done and then continues with its result. The caller gets control back at the first await that has to wait.
using System.Diagnostics;
var sw = Stopwatch.StartNew();
// Sequential: about 1.5 seconds
string a = await FetchAsync("users", 500);
string b = await FetchAsync("orders", 500);
string c = await FetchAsync("products", 500);
Console.WriteLine($"Sequential: {a}, {b}, {c} in {sw.ElapsedMilliseconds / 100 * 100} ms");
// Concurrent: about 0.5 seconds
sw.Restart();
Task<string> t1 = FetchAsync("users", 500);
Task<string> t2 = FetchAsync("orders", 500);
Task<string> t3 = FetchAsync("products", 500);
string[] results = await Task.WhenAll(t1, t2, t3);
Console.WriteLine($"Concurrent: {string.Join(", ", results)} in {sw.ElapsedMilliseconds / 100 * 100} ms");
// Exceptions travel through await
try
{
await FailAsync();
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Caught: {ex.Message}");
}
// Task.Run is for CPU-bound work
long sum = await Task.Run(() => SumSquares(5_000_000));
Console.WriteLine($"Sum of squares: {sum}");
static async Task<string> FetchAsync(string name, int delayMs)
{
await Task.Delay(delayMs); // stands in for a network call
return name;
}
static async Task FailAsync()
{
await Task.Delay(10);
throw new InvalidOperationException("Something broke after the await.");
}
static long SumSquares(int count)
{
long total = 0;
for (long i = 1; i <= count; i++) total += i * i;
return total;
}
Walking through it
The top-level statements can use await directly, because the compiler turns the file into an async Main. In the sequential part, each call waits for the one before. Total time: about 1.5 seconds. The three fetches do not depend on each other, so that is wasteful.
In the concurrent part, I call the three methods without awaiting. Each call starts and returns a running task. Then Task.WhenAll waits for all of them. Total time: about 0.5 seconds. This is the main practical benefit of async: starting independent operations together.
FailAsync throws after an await. The exception is stored in the task and rethrown at the await in the caller, so an ordinary try/catch works.
Task.Run queues work on a thread-pool thread. It is the right tool for CPU-heavy work, such as the loop of squares, when you do not want to block the calling thread. It is the wrong tool for waiting on I/O. In a web server, wrapping I/O in Task.Run just spends a thread you did not need to spend.
Rules that prevent most async bugs
- Async all the way. If a method awaits, make it async and return a Task, and have its callers await it. Do not mix styles.
- Never block on a task with
.Resultor.Wait(). In UI apps and old ASP.NET it can deadlock. Elsewhere it wastes the thread you meant to save. - Avoid
async void. It exists for event handlers only. An exception inside it cannot be caught by the caller and may crash the process. ReturnTaskinstead. - Name async methods with the
Asyncsuffix. It tells callers to await. - Do not forget to await. Calling an async method without awaiting it starts the work and ignores errors. The compiler warns you.
What the compiler does
An async method is rewritten into a state machine. Each await is a point where the method can suspend and later resume. You do not need the details. What helps is to know that it costs a small allocation, so do not make a method async if it only returns a task from another call without doing anything else. In that case, return the task directly. For the hottest paths, ValueTask<T> exists, but start with Task.
Common mistakes
- Awaiting in a loop when the operations could run together.
- Using
Task.Runaround async code "to make it async". - Blocking with
.Result. - Using
async voidoutside event handlers.
Try it yourself
- Change the sequential example so the second fetch needs the result of the first, for example it takes the name from the first. Observe why this one cannot run concurrently.
- Write
async Task<int> CountWordsAsync(string path)that reads a file withFile.ReadAllTextAsync. - Start ten delayed tasks with
Task.WhenAll, then useTask.WhenAnyto find which finishes first when the delays differ.
using System.Diagnostics;
var sw = Stopwatch.StartNew();
// Sequential: about 1.5 seconds
string a = await FetchAsync("users", 500);
string b = await FetchAsync("orders", 500);
string c = await FetchAsync("products", 500);
Console.WriteLine($"Sequential: {a}, {b}, {c} in {sw.ElapsedMilliseconds / 100 * 100} ms");
// Concurrent: about 0.5 seconds
sw.Restart();
Task<string> t1 = FetchAsync("users", 500);
Task<string> t2 = FetchAsync("orders", 500);
Task<string> t3 = FetchAsync("products", 500);
string[] results = await Task.WhenAll(t1, t2, t3);
Console.WriteLine($"Concurrent: {string.Join(", ", results)} in {sw.ElapsedMilliseconds / 100 * 100} ms");
// Exceptions travel through await
try
{
await FailAsync();
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Caught: {ex.Message}");
}
// Task.Run is for CPU-bound work
long sum = await Task.Run(() => SumSquares(5_000_000));
Console.WriteLine($"Sum of squares: {sum}");
static async Task<string> FetchAsync(string name, int delayMs)
{
await Task.Delay(delayMs); // stands in for a network call
return name;
}
static async Task FailAsync()
{
await Task.Delay(10);
throw new InvalidOperationException("Something broke after the await.");
}
static long SumSquares(int count)
{
long total = 0;
for (long i = 1; i <= count; i++) total += i * i;
return total;
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account