
Why async void Is Not Just async Task Without a Result
- كاتب موثّق
- .NET 10
محتويات المقال
InvalidOperationException that the job's try/catch was supposed to log. Nobody wrote async void anywhere, yet that's the cause. The guilty line is orderIds.ForEach(async id => await SaveOrderAsync(id)). ForEach takes an Action<int>, which returns void, so the compiler turns the async lambda into an async void method, once per order.
The common misconception
void versus Task is about the result. A method that returns nothing is void; its async version is async void. Task is extra ceremony for when you want to await, and if nobody needs to wait, async void is a lighter, equivalent choice.
void really does just mean "no result", and the async keyword seems to add asynchrony on top of the same signature. The compiler accepts async void anywhere without complaint. And Microsoft's own samples use it, because button-click handlers in WinForms and WPF are async void, and they work fine.
Task isn't a wrapper for a result. It's the caller's only connection to the work after the method returns. Remove it and you don't just lose the result: you lose completion, errors and composition.
What actually happens
A Task is the caller's only handle
async Task method reaches an await that has to wait, it returns an unfinished Task. That object tracks the rest of the work. The caller can await it to resume when the work is done, pass it to Task.WhenAll or Task.WhenAny, or store it and check it later. If the method throws, the exception is captured and stored in the task, then rethrown at the await, exactly where the caller's try/catch can handle it.
async void returns, and the caller believes it's done
async void method also returns at its first real wait, but it returns nothing. The caller continues immediately, with no way to know that work is still running. That's how the import job logged "Import complete" while every save was still in flight. In ASP.NET Core the effect is worse: an async void action lets the request complete at the first await, and when the method later writes to the response, Microsoft's docs warn that the late access crashes the process.
Its exceptions have nowhere to go
Task, there's no place to store an exception. So an exception that escapes an async void method, even one thrown before its first await, is raised directly on the that was current when the method started. In a UI app, that's the UI thread, the same place an exception from an ordinary event handler would surface. In ASP.NET Core, a worker service or a console app there's no context, so the exception is rethrown on a thread pool thread, where no code of yours can catch it: it's unhandled, and the process terminates. A try/catch around the call never sees it, because the call already returned.
How async void sneaks in
async void by accident. It usually arrives through a lambda. An async lambda takes the shape of the delegate it's converted to: passed where a Func<Task> is expected, it returns a Task; passed to an Action or Action<T>, it becomes async void. List<T>.ForEach, Parallel.ForEach, timer callbacks and custom events typed as Action all accept an async lambda without a warning, and every call is .
The import job, fixed
SaveOrderAsync is the same in both; only the loop changes:
List<int> orderIds = [1, 2, 3];try{ // ForEach takes an Action<int>, so this lambda is async void orderIds.ForEach(async id => await SaveOrderAsync(id)); Console.WriteLine("Import complete"); // printed before any save ends}catch (Exception ex){ Console.WriteLine($"Import failed: {ex.Message}"); // never runs}static async Task SaveOrderAsync(int id){ await Task.Delay(100); // stands in for the database call if (id == 2) throw new InvalidOperationException($"Order {id} rejected");}List<int> orderIds = [1, 2, 3];try{ // Select gives Func<int, Task>: one Task per order, all awaited await Task.WhenAll(orderIds.Select(SaveOrderAsync)); Console.WriteLine("Import complete"); // only after every save}catch (Exception ex){ Console.WriteLine($"Import failed: {ex.Message}"); // Order 2 rejected}static async Task SaveOrderAsync(int id){ await Task.Delay(100); // stands in for the database call if (id == 2) throw new InvalidOperationException($"Order {id} rejected");}foreach with await inside does the job.
async Task vs async void
async Task | async void | |
|---|---|---|
await | ||
Task, rethrown at await | ||
WhenAll and WhenAny? | ||
The one place it belongs: event handlers
void signature, and whoever raises the event doesn't wait for handlers anyway, so async void is the only option there and it behaves like an ordinary handler. Keep these handlers thin: catch everything, and move the real logic into an async Task method that you can call and test:
public class ExportButton(ILogger<ExportButton> logger){ public async void OnClick(object? sender, EventArgs e) { try { await ExportAsync(); // the real logic returns a Task } catch (Exception ex) { logger.LogError(ex, "Export failed"); } } public async Task ExportAsync() => await Task.Delay(100);}How to apply it in your project
Search for async void Search the codebase for async voidand change every method that isn't an event handler toasync Task. Then make every caller await the task it now gets back.Audit async lambdas Look for async lambdas passed to ForEach,Parallel.ForEach, timer callbacks and events or parameters typed asAction. Replace them withawait Task.WhenAll(...), aforeachwithawait, orParallel.ForEachAsync.Wrap the event handlers you keep Give every remaining async voidhandler atry/catchthat logs or shows the error, and keep its body to a singleawaitof anasync Taskmethod.Never fire and forget on a server In ASP.NET Core, return Taskfrom every endpoint and filter. Work that must outlive the request belongs in a hosted background service, not in anasync voidmethod or an unawaited task.
Key takeaways
The Taskan async method returns is how callers wait for it, catch its exceptions and combine it with other work;async voidgives all of that up.Exceptions from async voidbypass the caller'stry/catch; with noSynchronizationContext, they crash the process.Async lambdas passed to Actionparameters becomeasync voidwithout any warning.Use async voidonly for event handlers, keep them thin, and catch everything inside them.
📚 المصادر
Async return types: Void return type — Microsoft Learn Async/Await: Best Practices in Asynchronous Programming — Stephen Cleary, MSDN Magazine (Microsoft Learn archive) Asynchronous programming scenarios: Return async void only from event handlers — Microsoft Learn ASP.NET Core Best Practices: Do not use the HttpContext after the request is complete — Microsoft Learn
التعليقات (0)