Fire-and-forget tasks
Besides Task
and Task<T>,
we can declare an asynchronous method as void. It is useful in the case of top-level event handlers, for example, the button click or text changed handlers in the UI. An event handler that returns a value is possible, but is very inconvenient to use and does not make much sense.
So allowing async void
methods makes it possible to use await
inside such event handlers:
private async void button1_Click(object sender, EventArgs e) { await SomeAsyncStuff(); }
It seems that nothing bad is happening, and the C# compiler generates almost the same code as for the Task
returning method, but there is an important catch related to exceptions handling.
When an asynchronous method returns Task
, exceptions are connected ...
Get Mastering C# Concurrency now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.