I don't understand the difference between these two implementations of calling SendMailAsync. Much of the time with the first, I'm receiving a TaskCanceledException, but with the second, everything works as expected.
I thought the two consuming methods would be equivalent, but clearly I'm missing something.
This seems related to, but opposite from: TaskCanceledException when not awaiting
// Common SmtpEmailGateway library
public class SmtpEmailGateway : IEmailGateway
{
public Task SendEmailAsync(MailMessage mailMessage)
{
using (var smtpClient = new SmtpClient())
{
return smtpClient.SendMailAsync(mailMessage);
}
}
}
// Caller #1 code - Often throws TaskCanceledException
public async Task Caller1()
{
// setup code here
var smtpEmailGateway = new SmtpEmailGateway();
await smtpEmailGateway.SendEmailAsync(myMailMessage);
}
// Caller #2 code - No problems
public Task Caller2()
{
// setup code here
var smtpEmailGateway = new SmtpEmailGateway();
return smtpEmailGateway.SendEmailAsync(myMailMessage);
}
EDIT: It turns out the Caller2 method was also causing exceptions, I just wasn't seeing them due to the WebJobs framework this was being called by. Yuval's explanation cleared all of this up and is correct.