为什么 SmtpClient.SendAsync 不是异步的?
Why isn't SmtpClient.SendAsync async?
此方法被标记为异步但 returns 无效。它实际上是异步的,只是不是基于任务的吗?如果是,它是如何异步的?
在官方 docs 页面上有一些关于此方法的特定问题的信息。
To receive notification when the e-mail has been sent or the operation has been canceled, add an event handler to the SendCompleted
event.
这意味着方法不是阻塞的,但不能等待,因为它对 TPL 一无所知。您应该改为订阅 SendCompleted
事件。
通过 link 查看我提供的代码示例以查看可能的使用场景。
虽然 SendMailAsync
是使用基于任务的异步模式实现的,可能应该改用它。
如果您阅读了该代码,您可能忽略了 AsyncOpManager - 请参阅 https://github.com/dotnet/corefx/blob/master/src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs#L662 :)
然而,实际上,在下面的 switch
中,我们看到:
- SmtpDeliveryMethod.PickupDirectoryFromIis:总是抛出
- SmtpDeliveryMethod.SpecifiedPickupDirectory:似乎 100% 同步(直接调用
message.Send(_writer, true, allowUnicode)
和 writer.Close
和 _transport.ReleaseConnection
)
- SmtpDeliveryMethod.Network/default:似乎 100% 异步(
_transport.BeginGetConnection
开始操作,我没有看到任何等待或继续)
(至少如果我读得好代码,我没有在那里挖得太深)
此方法被标记为异步但 returns 无效。它实际上是异步的,只是不是基于任务的吗?如果是,它是如何异步的?
在官方 docs 页面上有一些关于此方法的特定问题的信息。
To receive notification when the e-mail has been sent or the operation has been canceled, add an event handler to the
SendCompleted
event.
这意味着方法不是阻塞的,但不能等待,因为它对 TPL 一无所知。您应该改为订阅 SendCompleted
事件。
通过 link 查看我提供的代码示例以查看可能的使用场景。
虽然 SendMailAsync
是使用基于任务的异步模式实现的,可能应该改用它。
如果您阅读了该代码,您可能忽略了 AsyncOpManager - 请参阅 https://github.com/dotnet/corefx/blob/master/src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs#L662 :)
然而,实际上,在下面的 switch
中,我们看到:
- SmtpDeliveryMethod.PickupDirectoryFromIis:总是抛出
- SmtpDeliveryMethod.SpecifiedPickupDirectory:似乎 100% 同步(直接调用
message.Send(_writer, true, allowUnicode)
和writer.Close
和_transport.ReleaseConnection
) - SmtpDeliveryMethod.Network/default:似乎 100% 异步(
_transport.BeginGetConnection
开始操作,我没有看到任何等待或继续)
(至少如果我读得好代码,我没有在那里挖得太深)