The problem with “async void”
Tags: microsoft, coding, dotnet, development
Published: 2024-05-28 08:00:00

The problem with using “async” and “void” in programming languages like C# is that it can lead to unexpected behavior and difficulties in error handling. Let’s take a closer look at why this is a problem:

We develop a small console application with the following flow:

1.) First, we issue a message (“Start”) on the console.

2.) Then, we start an asynchronous task that waits for one second before issuing the message “Wait one second” on the console.

3.) After the asynchronous task finishes waiting, it returns to the main thread.

4.) The main thread waits until the asynchronous task completes.

5.) Only when the task completes, the “End” message is displayed on the console.

In this way, we ensure that the application responds synchronously to the execution of the asynchronous task and continues only when the task completes.


![Code#1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0rax89pfcwqn6jykyys1.png)


![console#1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k1hkf943kcs24fktsnz0.png)



So far everything is running smoothly. However, I currently have to wait for the background task to complete. Even though it is an asynchronous operation that does not return a result, my program blocks until this task is fully completed.

But what if I wanted to implement a simple “fire & forget” method? What if I didn’t want to wait for the process to complete?

Theoretically, we could simply use the “void” return type in the background task instead of “task” and remove the “await” statement. This way, the method would execute asynchronously without waiting for the result. Would this be possible?

Yes, the compiler would not detect an error, and the application could still be started.

The output would look a little different than it does now, but that is exactly what is intended. We call the method without waiting.


![console#2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rswnfk1rbfsavfu7cni8.png)




The method should be called and our application should then continue without waiting for it to finish. This has been implemented correctly.

However, care should be taken because there is a danger here.

Let’s take a closer look at the background process:


![code 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x8sn9dbqf3bwqjgltowl.png)



In our example, not much is done in this phase. However, we should note what would happen if an error occurs inside this or another method or function is called in this method

Let’s add another one to our background task:


![code 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zifaxsz51ucxi3q54mt3.png)





In our extension an error occurs after a certain time, e.g. due to an incorrect execution of an operation.

How will our application react in this case?

This application will crash!

Can’t we solve the problem by implementing error handling?


![code4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/04adbzw66dzez1re1rrf.png)




Unfortunately, the problem is not solved by a simple implementation of error handling.

To explain this better, I would like to take a small diagram for help


![diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ze4wgutim3x864l1cni9.png)



The error occurs in the subthread without notifying the main thread, which causes the program to terminate.

Overall, you should use “async task” instead of “async void” to avoid the above problems. This allows you to wait for the async task to complete, retrieve results, and handle errors properly, resulting in more reliable and easier-to-maintain code.

However, if it is still necessary to perform a Fire&Forget operation, then use this:

```
…
//fire & forget

Task.Run(()=>{… do something here…});

…
```

**Keep attention**

I have found an approach that is also not the best way to deal with the task.

The problem here is the ForEach loop. Let’s take a look inside this loop.

This is the code from Microsoft: System.Collections.Generic


![code5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3x79terscjq1j78wnlns.png)



The param here is an action => method => no return value


![code5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7jgr1wj7urif0ts3zosm.png)



his means that we encounter the same problem here as described above.

## Summary:

**Loss of information:** If you declare a method as “async void,” it means that the method executes asynchronous code but does not return a value. This results in you not having access to the result of the method, even if it actually returns a result. It becomes difficult to use the result or pass it to other parts of your code. This can lead to behavior that is difficult to understand, especially when coordinating asynchronous operations.

**Leaving the logical flow:** By using “async void” the application leaves the logical flow of the application at the point where this method is called and is processed uncontrolled. This is because the method with async void does not have a return value that can be monitored.

**Missing return values:** In C# and other programming languages, it is a best practice to declare methods that contain asynchronous code with “async task”. This signals that the method returns a task that allows you to monitor the asynchronous operation and wait for its completion if necessary. The absence of a return value with “async void” results in a limitation of your control over the asynchronous code.

**Lack of error handling:** When an async void method raises an exception, the exception is not caught or handled. This means that errors in the method go unhandled and can potentially crash the entire application process. In an asynchronous task, on the other hand, you can catch exceptions and respond accordingly.