DEV Community

PeterMilovcik
PeterMilovcik

Posted on

4

One Good Reason Why You Should Not Use Async Void

Let's take a look at this little example.

class Program
{
    static void Main(string[] args)
    {
        try
        {
            AsyncVoidMethod();
            Console.WriteLine("No exception is thrown!");
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }

    private static async void AsyncVoidMethod()
    {
        throw new Exception("BOOM!");
    }
}
Enter fullscreen mode Exit fullscreen mode

What we have here is a method AsyncVoidMethod, which throws an exception and returns async void instead of async Task.

Since it's void, we cannot await it. What it also means that exception from an async call could not be saved anywhere because there is no Task object which could save it.

Output

No exception is thrown!

It's a dangerous problem: an exception is not handled!

Solution

I wouldn't like to describe a solution here, because John Thiriet already did a great job doing so, and you know, that duplication is evil, right?

Check this fantastic article for solution:
https://johnthiriet.com/removing-async-void/

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (1)

Collapse
 
roubachof profile image
Jean-Marie Alfonsi

Hey man! Great subject!
I also created my own component to handle async void and process global error handler, statistic, ...

github.com/roubachof/Sharpnado.Tas...

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay