简体   繁体   English

为什么SmtpClient.SendAsync不异步?

[英]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 参考: 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. 此方法标记为异步,但返回void。 Is it actually asynchronous and just isn't Task based? 它实际上是异步的,并且不是基于任务的吗? If so, how is it asynchronous? 如果是这样,它如何异步?

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. 若要在发送电子邮件或取消操作时接收通知,请将事件处理程序添加到SendCompleted事件中。

It means method is not blocking, but can't be awaited, because it knows nothing about TPL. 这意味着方法没有阻塞,但不能等待,因为它对TPL一无所知。 You should subscribe to a SendCompleted event instead. 您应该改为订阅SendCompleted事件。 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. 尽管SendMailAsync是通过基于任务的异步模式实现的,可能应该代替使用它。

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 :) 如果您阅读该代码,则可能忽略了AsyncOpManager-请参阅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: 但是,实际上,在下面的switch中,我们看到:

  • SmtpDeliveryMethod.PickupDirectoryFromIis: always throws SmtpDeliveryMethod.PickupDirectoryFromIis:总是抛出
  • SmtpDeliveryMethod.SpecifiedPickupDirectory: seems 100% synchronous (direct call to message.Send(_writer, true, allowUnicode) and writer.Close and _transport.ReleaseConnection ) SmtpDeliveryMethod.SpecifiedPickupDirectory:似乎100%同步(直接调用message.Send(_writer, true, allowUnicode)writer.Close_transport.ReleaseConnection
  • SmtpDeliveryMethod.Network/default: seems 100% asynchronous ( _transport.BeginGetConnection starts operation, I don't see any wait or continuation) SmtpDeliveryMethod.Network/default:似乎100%异步( _transport.BeginGetConnection开始运行,我看不到任何等待或继续)

(at least if I read the code well, I didn't dig too deep there) (至少,如果我很好地阅读了代码,我并没有在那儿钻得太深)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM