skip to content

Why should a C# async method return Task rather than void, and what happens when an exception escapes an async void method?

level: middleimportance: must knowfreq 75%

answer

  1. nothing to await
  2. no task to hold the exception
  3. event handlers are the exception
  4. rethrown where it started
  5. a console app has no context

basics

~20 s

An async void method gives callers no Task, so they cannot await it, learn when it finished, or catch its exceptions. An escaping exception is rethrown on the captured SynchronizationContext or, without one, on the thread pool, which terminates the process.

solid answer

~40 s

An `async Task` method stores any exception in the returned task, and the caller sees it at `await`. An `async void` method has no task to store it in, so the compiler-generated builder rethrows the exception asynchronously: posted to the `SynchronizationContext` that was current when the method started, or, if there was none (a console app, a worker), queued to the thread pool, where an unhandled exception terminates the process. A `try`/`catch` around the call never sees it, because the call has already returned, and that holds even for a throw before the first `await`. `async void` exists for **event handlers**, whose delegate types such as `EventHandler` require a `void` return. Everywhere else return `Task`, and in a handler catch everything inside the body.

code

csharp · 21 lines
csharp
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
    Console.WriteLine($"UnhandledException: {((Exception)e.ExceptionObject).Message} (IsTerminating = {e.IsTerminating})");

try
{
    OnRefreshClicked(null, EventArgs.Empty); // what a button's Click event would invoke
    Console.WriteLine("handler call returned; the try block finished without an exception");
}
catch (Exception ex)
{
    Console.WriteLine($"caught: {ex.Message}"); // never runs
}

await Task.Delay(1000);
Console.WriteLine("never printed: the process has already terminated");

static async void OnRefreshClicked(object? sender, EventArgs e)
{
    await Task.Delay(100); // the call to the weather service
    throw new InvalidOperationException("weather service returned 503");
}

go deeper

for a junior

Recall the rule: return Task from async methods that produce no value; use async void only for event handlers.

for a middle

Explain where the exception goes: posted to the captured SynchronizationContext, or queued to the thread pool, which ends a console process, and why the caller's try/catch never sees it.

for a senior

Show how you find hidden async void in a code review, such as async lambdas passed to Action parameters like List<T>.ForEach, and how you harden the handlers that must stay.

for a principal

Turn it into team practice: an analyzer or review rule that flags async void outside event handlers, and a standard handler shape that logs and reports every failure.

## Three return shapes for an async method An async method in C# may declare one of three shapes when it produces no value or one value (task-like types such as `ValueTask` and async streams aside): | Declared return | Can the caller await it? | Where an escaping exception goes | |---|---|---| | `Task` | yes | stored in the task, rethrown at `await` | | `Task<T>` | yes, and gets the `T` | stored in the task, rethrown at `await` | | `void` | no | rethrown asynchronously, outside any caller | Microsoft's guidance on async return types is direct: use `void` for asynchronous **event handlers**, which require a `void` return, and return `Task` from every other method that produces no value, because a `void`-returning async method cannot be awaited. ## Where an async void exception goes When an exception leaves the body of an `async void` method, the code the compiler generated catches it and hands it to the method's builder, `AsyncVoidMethodBuilder`. That builder has no task to store it in, so in the .NET 10 runtime source its `SetException` does one of two things: 1. If a **`SynchronizationContext`** was current when the method started (a desktop UI thread, for instance), the exception is **posted** to that context and rethrown there, which sends it to the UI framework's unhandled-exception handling. 2. If there was **no context** (a console tool, a worker service, any thread-pool thread), the exception is **queued to the thread pool** and rethrown on a pool thread. An unhandled exception on a pool thread ends the process. Two consequences follow, and both show up in interviews: - A **`try`/`catch` around the call cannot catch it.** The call returned normally long before the exception was rethrown somewhere else. - This is true **even for a throw before the first `await`.** The generated code catches that exception too and routes it through the builder, so a caller that expects at least the synchronous part to throw into its `catch` is wrong. Running such a method from a console app prints the caller's "returned" line and then dies. ## Seeing it crash The code example below simulates a "Refresh" button in a weather client from a console app. The handler awaits the service call, which then fails. The output shows the `try` block finishing normally, `AppDomain.UnhandledException` reporting the exception with `IsTerminating = True`, and the runtime's own `Unhandled exception.` report. The line after `await Task.Delay(1000)` never prints, because the process has already ended. An `async Task` version of the same method would simply have produced a faulted task. If no code ever awaited that task, the exception would be **unobserved** rather than fatal; what happens to unobserved task exceptions is covered with task combinators and failures. ## When async void is legitimate - **Event handlers.** A button's `Click` event is typically declared with `EventHandler`, which returns `void`, so `async void OnRefreshClicked(object? sender, EventArgs e)` is the only way to await inside it. - **Overrides with a fixed void signature** imposed by a framework you cannot change, which is the same situation in another form. For those cases the house pattern is: 1. Keep the handler thin: catch every exception inside it, log it, and show the user something. 2. Move the real work into a method that returns `Task`, so it can be awaited, composed and tested. ```csharp async void OnRefreshClicked(object? sender, EventArgs e) { try { await RefreshForecastAsync(); } catch (Exception ex) { ShowError(ex); } } ``` ## Hidden async void `async void` also appears without being written. An async lambda passed where an `Action` is expected becomes an async void lambda. `List<T>.ForEach` takes an `Action<T>`, so `ids.ForEach(async id => await SaveAsync(id))` compiles, starts every save, and returns before any of them finishes, with each failure able to crash the process. Use a `foreach` loop with `await` inside, or collect the tasks and await them together. Test code has the same trap. A test method declared `async void` cannot be awaited by the test runner, so the runner cannot reliably observe its completion or its failure. Declare async tests as `async Task`.

  • Is an exception thrown before the first await in an async void method caught by the caller's try/catch?
    No. The compiler-generated code catches every exception from the body, including one thrown on the first line, and passes it to the async void builder, which rethrows it on the captured `SynchronizationContext` or the thread pool. The call returns normally and, in a console app, the process terminates moments later.
  • How do you write an async event handler safely?
    Keep it as the only `async void` in the flow, wrap its whole body in `try`/`catch`, and report the error to the user or a log. Put the real work in a `Task`-returning method that the handler awaits, so the logic stays awaitable and testable.
  • Why does `ids.ForEach(async id => await SaveAsync(id))` finish before the saves do?
    `List<T>.ForEach` accepts an `Action<T>`, so the async lambda is converted to an async void delegate. `ForEach` invokes each one, gets nothing back to wait on, and returns while the saves are still running. A `foreach` with `await` inside, or awaiting the collected tasks, fixes it.

  • A try/catch around the call catches exceptions from an async void method
  • async void is fine for any async method that produces no value
  • An async void exception is silently ignored, like an unobserved task
  • Only exceptions after the first await escape an async void method
  • Callers can await an async void method like any other async method