Sobes.tech
Middle+

Why is async void considered bad practice?

sobes.tech AI

Answer from AI

async void in C# is considered bad practice for several reasons:

  • Lack of ability to track method completion. Methods with return type Task or Task<T> allow awaiting their completion (await), but async void does not.

  • Problems with exception handling. Exceptions thrown in async void methods cannot be caught with try-catch in the calling code and can lead to application crashes.

  • Testing difficulties. async void methods are hard to test because you cannot await their completion.

  • Use only for event handlers. The only acceptable case is event handlers, where the signature requires void.

Example of bad practice:

async void DoWork()
{
    await Task.Delay(1000);
    throw new Exception("Error");
}

// Call
DoWork();
// Exception will not be caught here

The correct approach is to return Task:

async Task DoWorkAsync()
{
    await Task.Delay(1000);
    throw new Exception("Error");
}

// Call
try
{
    await DoWorkAsync();
}
catch (Exception ex)
{
    // Handle exception
}

Thus, async void should only be used for events, and elsewhere always return Task.