🎓 A1Learner
🔍
0 of 38 lessons completed

C# Async and Await

An async method is a method that can pause while an operation runs and resume when that operation finishes. The async and await keywords mark the method and its waiting points.

Wait, Then Print

The PrintLater method awaits a delay before it prints. Main waits for PrintLater before it prints its own line.

using System;
using System.Threading.Tasks;

class Program
{
    static async Task PrintLater()
    {
        await Task.Delay(10);
        Console.WriteLine("Done waiting");
    }

    static async Task Main(string[] args)
    {
        await PrintLater();
        Console.WriteLine("After the call");
    }
}

An Await Inside Main

Main is asynchronous in this program. It prints, waits, and then prints again.

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("Starting");
        await Task.Delay(10);
        Console.WriteLine("Finished");
    }
}

Two Awaits in Order

Main awaits Step twice in a row. The steps print in the order Main awaits them.

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Step(string name)
    {
        await Task.Delay(10);
        Console.WriteLine(name);
    }

    static async Task Main(string[] args)
    {
        await Step("First step");
        await Step("Second step");
        Console.WriteLine("Both done");
    }
}

Example

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Load()
    {
        await Task.Delay(10);
        Console.WriteLine("Loaded");
    }

    static async Task Save()
    {
        await Task.Delay(10);
        Console.WriteLine("Saved");
    }

    static async Task Main(string[] args)
    {
        await Load();
        await Save();
        Console.WriteLine("Report ready");
    }
}

Key points

  • The async keyword marks a method as asynchronous.
  • An asynchronous method with no result returns a Task.
  • Main itself can return a Task; the runtime waits for it.
  • The await keyword pauses the method until the awaited operation finishes.
  • Lines after an await run only after that operation finishes.
  • Task.Delay creates a short wait that a method can await.
  • System.Threading.Tasks provides the Task type and Task.Delay.

In this example, Main awaits Load and then awaits Save. Load waits and prints Loaded. Save waits and prints Saved. The last line prints only after both methods finish.

Note

Two awaits in a row finish in program order, first await first.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does await do in an async method?