C# Academy · Lesson

Async and Await: Working with Asynchronous Code

Master asynchronous programming to build responsive applications.

Lesson 2 of 510 steps

Async and Await: Working with Asynchronous Code is a free C# Academy lesson on CoddyKit. This is lesson 2 of 5. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, and your progress syncs across the web and the CoddyKit app. The C# Academy course includes 5 lessons in total.

Introduction to Async and Await

Async and Await: Working with Asynchronous Code

Welcome to the next lesson! In this lesson, you’ll learn how to use async and await in C# to write asynchronous code that improves application responsiveness and performance. Let’s get started!

Async and Await: Working with Asynchronous Code — illustration 1

What is Asynchronous Programming?

Asynchronous programming allows tasks to run independently without blocking the main thread. This is especially useful for tasks like reading files, fetching data from the internet, or interacting with databases.

Key Point: Asynchronous code improves application responsiveness, especially in UI and server applications.

Understanding Async and Await

Async and await are keywords in C# that simplify asynchronous programming:

  • async: Marks a method as asynchronous.
  • await: Pauses the execution of the method until the awaited task completes.

Key Point: Async methods always return a Task or Task<T>.

Creating an Async Method

Let’s create an asynchronous method to simulate a long-running task. Example:

Tip: Use Task.Delay() to simulate delays in asynchronous operations.

using System;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        Console.WriteLine("Starting task...");
        await PerformTask();
        Console.WriteLine("Task completed!");
    }

    static async Task PerformTask() {
        await Task.Delay(3000); // Simulates a 3-second delay
        Console.WriteLine("Task is running...");
    }
}

Returning a Value from an Async Method

Async methods can return values using Task<T>. Example:

using System;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        int result = await CalculateSumAsync(10, 20);
        Console.WriteLine("Result: " + result);
    }

    static async Task<int> CalculateSumAsync(int a, int b) {
        await Task.Delay(1000); // Simulates a delay
        return a + b;
    }
}

Handling Exceptions in Async Code

Use try-catch to handle exceptions in asynchronous methods. Example:

using System;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        try {
            await DivideAsync(10, 0);
        } catch (Exception ex) {
            Console.WriteLine("Error: " + ex.Message);
        }
    }

    static async Task DivideAsync(int a, int b) {
        await Task.Delay(1000);
        if (b == 0) throw new DivideByZeroException("Cannot divide by zero.");
        Console.WriteLine("Result: " + (a / b));
    }
}

Practice Challenge

Create an asynchronous method that fetches data from a URL and displays its content. Example:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        string url = "https://jsonplaceholder.typicode.com/todos/1";
        string data = await FetchDataAsync(url);
        Console.WriteLine("Data: " + data);
    }

    static async Task<string> FetchDataAsync(string url) {
        using HttpClient client = new HttpClient();
        return await client.GetStringAsync(url);
    }
}

Best Practices for Asynchronous Programming

Here are some best practices:

  • Use async and await for tasks that involve I/O operations or long-running computations.
  • Avoid blocking asynchronous code with .Result or .Wait().
  • Handle exceptions to prevent unhandled errors.
  • Use ConfigureAwait(false) in library code to avoid deadlocks.

Tip: Keep your async methods concise and focused on a single responsibility.

Great Job!

Congratulations! You’ve learned how to use async and await to write asynchronous code in C#. In the next lesson, we’ll explore threading and tasks for parallel programming. Let’s keep coding!

Click Continue to move to the next lesson.

Async and Await: Working with Asynchronous Code — illustration 10
Free to start

Learn C# with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
93
Lessons
346

Frequently Asked Questions

Is the “Async and Await: Working with Asynchronous Code” lesson free?

Yes — the full text of “Async and Await: Working with Asynchronous Code” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO. The C# Academy course includes 5 lessons in total.

What will I learn in “Async and Await: Working with Asynchronous Code”?

Master asynchronous programming to build responsive applications. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 5.

How long does the “Async and Await: Working with Asynchronous Code” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Generics in C#
  2. Async and Await: Working with Asynchronous Code
  3. Understanding Threading and Tasks
  4. Exploring Delegates and Lambdas
  5. Understanding Reflection in C#
← Back to C# Academy