-
Book Overview & Buying
-
Table Of Contents
Mastering C# Concurrency
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 to this task and can be handled both by TPL and the try/catch block in case await is used. However, if we have a async void method, we have no Task to attach the exceptions to and those exceptions just get posted to the current synchronization...
Change the font size
Change margin width
Change background colour