will
will

Reputation: 1511

Why isn't SmtpClient.SendAsync async?

Reference: https://github.com/dotnet/corefx/blob/master/src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs#L583

This method is marked as asynchronous but returns void. Is it actually asynchronous and just isn't Task based? If so, how is it asynchronous?

Upvotes: 2

Views: 1497

Answers (2)

quetzalcoatl
quetzalcoatl

Reputation: 33506

If you read that code, you probably overlooked AsyncOpManager - see https://github.com/dotnet/corefx/blob/master/src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs#L662 :)

However, in fact, in a switch just below, we see that:

  • SmtpDeliveryMethod.PickupDirectoryFromIis: always throws
  • SmtpDeliveryMethod.SpecifiedPickupDirectory: seems 100% synchronous (direct call to message.Send(_writer, true, allowUnicode) and writer.Close and _transport.ReleaseConnection)
  • SmtpDeliveryMethod.Network/default: seems 100% asynchronous (_transport.BeginGetConnection starts operation, I don't see any wait or continuation)

(at least if I read the code well, I didn't dig too deep there)

Upvotes: 0

Uladz
Uladz

Reputation: 1968

There is some info about your particular question on this method at the official docs page.

To receive notification when the e-mail has been sent or the operation has been canceled, add an event handler to the SendCompleted event.

It means method is not blocking, but can't be awaited, because it knows nothing about TPL. You should subscribe to a SendCompleted event instead. Check the code example by link I've provided to see possible usage scenario.

While SendMailAsync is implemented with task based asynchronous pattern and, probably, should be used instead.

Upvotes: 6

Related Questions