CodeBlanks Logo Icon CodeBlanks

What is async/await?

C# course · Advanced · Lesson 1/83

Learn how the async and await keywords work.

What is async/await?

async/await is C#'s way of running long operations without blocking the thread. You mark a method with async; inside the body you use await to wait for a Task to finish.

While waiting, the thread is freed to do other work. When the work completes, the runtime resumes you where you awaited. This lets network and file operations run without freezing the user interface.

Synchronous and asynchronous flow

Synchronous code runs each line in order; nothing starts until the previous finishes. Asynchronous code starts a Task, moves on while it runs, and comes back when done.

For example, downloading a web page synchronously blocks and freezes the user interface. Asynchronous code can serve other requests while waiting; that is why modern apps are designed asynchronously.

Exercise Define the async Greet method

Define an async Task<string> Greet() method. In its body call await Task.CompletedTask and return "Hello". In Main call await Greet() to get the result and print it with Console.WriteLine.

Show example solution
Define async Task<string> Greet(); in the body write await Task.CompletedTask and return "Hello". In Main write string msg = await Greet(); Console.WriteLine(msg);
Example solution:
using System;
using System.Threading.Tasks;

class Program
{
    static async Task<string> Greet()
    {
        await Task.CompletedTask;
        return "Hello";
    }

    static async Task Main()
    {
        string msg = await Greet();
        Console.WriteLine(msg);
    }
}

Test yourself

  1. Which keyword marks a method that can use await?

    • static
    • async
    • await
    • Task
    Show answer

    async — Correct. A method marked with async can use await in its body.

  2. Complete the async method

    static ____ Task Hello() { return Task.CompletedTask; }
    Show answer
    static async Task Hello() { return Task.CompletedTask; }
  3. What does await do?

    • It immediately exits the method
    • It starts a new thread
    • It waits until the Task completes and gives the result
    • It cancels the Task
    Show answer

    It waits until the Task completes and gives the result — Correct. await waits until the Task is done and returns its result.

All lessons in Advanced