Breaking

Monday, September 13, 2021

The ‘async void’ trap

A colleague contacted me that he had trouble using a library I created. This library is used to abstract away the used mailing system. He told me that when the mail couldn’t be send succesfully, the error message got lost and that the library doesn’t return anything useful.

I started by running my integration test suite against this library(these are the moments you are extremely happy that you’ve spend so much time on writing tests) but all tests returned green.

I’ll asked the colleague to send me the code he was using. Do you notice what’s wrong?

public async void SendNotification(string from, string to, string subject, string body, bool isHtml, CancellationToken cancellationToken)
{
var mail = new Mail();
mail.FromAddress = new MailAddress(from);
mail.ToAddress.Add(new MailAddress(to)); // TESTING
mail.Subject = subject;
mail.Body = new MailBody() { Body = body, IsHtml = isHtml };
await _mailClient.SendMailAsync(mail);
}

The title of this post already gives you the answer. He was using ‘async void’ instead of ‘async Task’. ‘async void’ should only be used by event handlers.

I recommended using AsyncFixer to avoid this kind of issues in the future.

No comments:

Post a Comment