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
