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
TaskorTask<T>allow awaiting their completion (await), butasync voiddoes not. -
Problems with exception handling. Exceptions thrown in
async voidmethods cannot be caught withtry-catchin the calling code and can lead to application crashes. -
Testing difficulties.
async voidmethods 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.