Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. async / await

async / await

Since: C# 5.0(2012)

Keywords for defining and calling asynchronous methods. Use async to make a method asynchronous, and await to wait for an asynchronous operation to complete.

Syntax

async Task MethodName()
{
    await asyncOperation;
}

// Define an async method (with return value)
async Task<T> MethodName()
{
    T result = await asyncOperation;
    return result;
}

// Call an async method
await MethodName();
T value = await MethodName();

Keywords and Types

Keyword / TypeDescription
asyncDeclares a method as asynchronous, enabling the use of await inside it.
awaitWaits for an asynchronous operation to complete without blocking the thread, returning control to the caller.
TaskRepresents an asynchronous operation with no return value.
Task<T>Represents an asynchronous operation that returns a value of type T.
ValueTask<T>A lightweight asynchronous type that reduces heap allocations, useful when the operation completes synchronously most of the time.
async voidAn asynchronous method reserved for event handlers. Requires careful handling outside of event handlers, as exceptions cannot propagate to the caller.

Sample Code

PrintGreetingAsync() is an async method with no return value (async Task). AddAsync() is an async method with a return value (async Task<T>).

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

async Task PrintGreetingAsync(string name)
{
    await Task.Delay(100); // Simulates a 100ms delay.
    Console.WriteLine($"Hello, {name}!");
}

async Task<int> AddAsync(int a, int b)
{
    await Task.Delay(50); // Simulates an async operation.
    return a + b;
}

// Run multiple async operations sequentially.
async Task RunSequentialAsync()
{
    await PrintGreetingAsync("Kiryu Kazuma");
    await PrintGreetingAsync("Majima Goro");
    int result = await AddAsync(3, 4);
    Console.WriteLine($"3 + 4 = {result}");
}

// Entry point (.NET 5 and later allow async Main)
await RunSequentialAsync();
Console.WriteLine("Done");

Run the following command:

dotnet script async_await.csx
Hello, Kiryu Kazuma!
Hello, Majima Goro!
3 + 4 = 7
Done

Practical Pattern: Parallel Execution with Task.WhenAll

ParallelAsync.cs
using System;
using System.Threading.Tasks;

// Run multiple async operations in parallel.
async Task<string> FetchDataAsync(string name, int delayMs)
{
    await Task.Delay(delayMs);
    return $"Data for {name}";
}

// Task.WhenAll: waits for all tasks to complete in parallel.
async Task RunParallelAsync()
{
    var sw = System.Diagnostics.Stopwatch.StartNew();

    // Start three tasks at the same time.
    Task<string> task1 = FetchDataAsync("Kiryu Kazuma", 1000);
    Task<string> task2 = FetchDataAsync("Majima Goro", 1500);
    Task<string> task3 = FetchDataAsync("Akiyama Shun", 800);

    // Wait for all tasks in parallel (completes in ~1500ms, the longest task).
    string[] results = await Task.WhenAll(task1, task2, task3);

    foreach (var result in results)
        Console.WriteLine(result);

    Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds}ms"); // ~1500ms
}

await RunParallelAsync();

Run the following command:

dotnet script ParallelAsync.csx
Data for Kiryu Kazuma
Data for Majima Goro
Data for Akiyama Shun
Elapsed: 1521ms

Running sequentially with three separate await calls would take 3300ms total. Using Task.WhenAll() for parallel execution completes in approximately 1500ms — the duration of the longest task.

Common Mistakes

Common mistake 1: async void

Do not use async void outside of event handlers. Exceptions cannot propagate to the caller, which can crash the application.

using System;
using System.Threading.Tasks;

// NG: Do not use async void outside of event handlers.
async void FetchDataBad()
{
    await Task.Delay(100);
    throw new Exception("Error!"); // The caller cannot catch this.
}

Run the following command:

dotnet run
Unhandled exception. System.Exception: Error!
   at Program.<>c__DisplayClass0_0.<<Main>$>b__0() in Program.cs:line 8
Process terminated. Unhandled exception.

The following example demonstrates this:

// OK: Return async Task in all other cases.
async Task FetchDataGood()
{
    await Task.Delay(100);
    throw new Exception("Error!"); // The caller can catch this.
}

Common mistake 2: deadlock with .Result

Using .Result or .Wait() can cause a deadlock, especially in environments with a synchronization context such as ASP.NET or UI frameworks.

// NG: Using .Result or .Wait() can cause a deadlock.
var result = FetchDataGood().Result; // deadlock risk

The corrected version is:

// OK: Always use await.
var result = await FetchDataGood();

Common mistake 3: forgetting await

Forgetting await causes the code to continue without waiting for completion. The compiler issues a CS4014 warning.

// NG: Forgetting await causes the code to continue without waiting for completion.
async Task Main()
{
    FetchDataGood(); // no await — the task is not awaited.
    Console.WriteLine("Done"); // may print before data is fetched.
}

Run the following command:

warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed
Done

The following example demonstrates this:

// OK: Always add await.
async Task Main()
{
    await FetchDataGood();
    Console.WriteLine("Done");
}

Notes

Using async/await lets you wait for time-consuming operations (such as network or file I/O) to complete without blocking the thread. At each await point, the thread is released and the remaining code resumes after the operation finishes.

Do not use async void outside of event handlers. Exceptions thrown inside an async void method cannot propagate to the caller, which can cause the application to crash. Returning async Task propagates exceptions to the caller.

To run multiple async operations in parallel, see Task.Run() / Task.Delay() / Task.WhenAll(). For exception handling inside async methods, see Exception Handling and Async.

If you find any errors or copyright issues, please .