liveBook · Manning

Async void method

As explained in C# Concurrency: Asynchronous and multithreaded programming

An async void method is a C# asynchronous method with a void return type that cannot expose a Task representing its completion or failure.

An async void method starts asynchronous work without returning a Task that represents completion or carries failure to its caller. This fits event handlers, whose callers expect prompt control return, but makes completion and exception handling the method’s responsibility. section 3.4

Use async void only when the surrounding API requires it:

  • Reserve it for event handlers with a void-based signature. section 3.4
  • Catch every exception inside the method; an unhandled exception can reach the SynchronizationContext and crash the program. section 12.4
  • Prefer Task-returning methods when callers need completion, failure reporting, composition, or awaiting. section 3.4
Listing 3.4 async event handler
private async void Button1_Click(object sender, EventArgs ea)
{
  var text = await File.ReadAllTextAsync("source.txt");
  await File.WriteAllTextAsync("dest.txt", text);
}

A file-copying button handler demonstrates the permitted event-handler use: read asynchronously, then write asynchronously. section 3.4

Listing 3.6 async event handler with error handling
private async void Button1_Click(object sender, EventArgs ea)
{
  try
  {
     var text = await File.ReadAllTextAsync("source.txt");
     await File.WriteAllTextAsync("dest.txt", text);
  }
  catch(Exception ex)
  {
     // Do something with the exception
  }
}

The guarded version catches failures around both asynchronous file operations instead of allowing them to escape. section 3.4

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains missing Task-based exception propagation and SynchronizationContext bubbling, then prescribes explicit catches.
Examples
Demonstrates a button handler that asynchronously reads source.txt, writes dest.txt, and catches exceptions.
What it assumes
Assumes familiarity with async/await, Task, exceptions, and SynchronizationContext.
What you can do after
Apply it via C# event handlers while catching every exception inside the method.
How it connects
Connects async void to event handlers, Task, await, exceptions, and SynchronizationContext.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.