SendAsyncCancel 是否取消 SendMailAsync?

Does SendAsyncCancel cancel SendMailAsync?

SmtpClientclass中,SendAsyncCancel是否取消了SendMailAsync方法?

我在 www 上看到了一些代码示例,暗示它确实如此。

但是MSDN says,

Use the SendAsyncCancel method to cancel a pending SendAsync operation. If there is mail waiting to be sent, this method releases resources used to store the mail. If there is no mail waiting to be sent, this method does nothing.

... 这意味着它取消了 SendAsync 而不是 SendMailAsync.

有没有办法取消SendMailAsync?如果不是,为什么不呢?

如果您想取消异步发送(因此使用旧的 SendAsync 而不是较新的 SendMailAsync),使用 SendAsync 而不是 [= 的其他缺点是什么12=]?

我试图从 ASP 网页的 post-back 处理程序调用 SendMailAsync,但它引发了异常:

System.InvalidOperationException: Asynchronous operations are not allowed in this context. Page starting an asynchronous operation has to have the Async attribute set to true and an asynchronous operation can only be started on a page prior to PreRenderComplete event.
   at System.Web.LegacyAspNetSynchronizationContext.OperationStarted()
   at System.ComponentModel.AsyncOperation.CreateOperation(Object userSuppliedState, SynchronizationContext syncContext)
   at System.Net.Mail.SmtpClient.SendAsync(MailMessage message, Object userToken)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.SendAsync(MailMessage message, Object userToken)
   at System.Net.Mail.SmtpClient.SendMailAsync(MailMessage message)
   at MyWebSite.AdminTest.TestEmail.<sendAsynchronous>d__9.MoveNext()

由此我推断出两点:

  1. SendMailAsync 确实是使用 SendAsync 实现的(您可以在异常的调用堆栈上看到它)。因此,SendAsyncCancel 大概也适用于 SendMailAsync。
  2. 除非您想处理 "Asynchronous operations are not allowed in this context" 问题,否则不能从 ASP 调用 SendMailAsync。那是 discussed here,看起来可能很乱。而我猜想调用 SendAsync 可能没有这个问题(因为我在其他地方使用 HttpClient.SendAsyncContinueWith,最后有一个 CountdownEvent.Wait 来等待操作完成,没有看到抛出这个异常)。

SendMailAsync 可以在通过 HostingEnvironment.QueueBackgroundWorkItem 调用时使用。