Avoiding the async void return type in scripts

There are three possible return types for asynchronous methods: Task, Task<T>, and void. We don't recommend async void, because it's used for asynchronous methods that don't return a result and are often triggered by events, which can create issues.

When using Task and Task<T> return types, however, exceptions are captured in the Task and Task<T> and only raised when awaited. This allows proper error handling and makes it easier to test. In contrast, with the async void return type, exceptions are sent directly to the global exception handler, which can crash the application without the chance to handle the error gracefully.

Additionally, Task and Task<T> return types can be awaited and tracked, allowing you to chain asynchronous operations and manage errors effectively. This makes them ideal for unit testing. In contrast, async void return types don’t return a Task or Task<T>, so the caller cannot await or control their execution, making testing difficult and leading to potential issues with timing and race conditions.

Do you have some feedback for us?

If you have suggestions for improving this article,