C# Foundations·C# from first file to first API

Async and error handling

Asynchronous code keeps a service responsive; exceptions are part of the contract.

Beginner 14 min read Lesson 9 of 300 Challenge included
What you will be able to do
  • An async method should end in Async by convention.
  • Use CancellationToken to stop work when the caller disconnects.
  • Log exceptions with context; return a stable error code.

In plain English

Use async and await for I/O, not for CPU work. Do not block with .Result. Catch only errors you can handle, use typed exceptions or result types for expected failures, and never expose an internal exception message to a client.

Loading.csC#
public async Task<Course?> LoadAsync(string slug, CancellationToken token)
{
    try
    {
        return await db.Courses
            .FirstOrDefaultAsync(course => course.Slug == slug, token);
    }
    catch (OperationCanceledException)
    {
        return null;
    }
}

var course = await LoadAsync("html", CancellationToken.None);
Your turn

Handle cancellation

Medium

Write an async method that loads a course and returns null when cancellation is requested.

CSHARP · starter
public async Task<Course?> LoadAsync(CancellationToken token)
{
}
Check your understanding before moving on.
Knowledge checkQuestion 1

What is the purpose of CancellationToken?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: A minimal ASP.NET API
Lesson 9 of 300 · 0% of course