在SmtpClient
课程中,SendAsyncCancel
取消了SendMailAsync
方法吗?
我在www上看到一些代码示例,暗示它的含义。
然而MSDN says,
使用SendAsyncCancel方法取消挂起的SendAsync操作。如果有邮件等待发送,则此方法释放用于存储邮件的资源。如果没有邮件等待发送,则此方法不执行任何操作。
...这意味着取消SendAsync
但不取消SendMailAsync
。
有没有办法取消SendMailAsync
?如果没有,为什么不呢?
如果要取消异步发送(因此使用旧的SendAsync
而不是较新的SendMailAsync
),使用SendAsync
代替SendMailAsync
会有什么其他缺点}?
答案 0 :(得分:0)
我试图从ASP网页的回发后处理程序调用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()
由此我推断出两件事:
HttpClient.SendAsync
和ContinueWith
,最后用CountdownEvent.Wait
等待操作完成,没有看到抛出此异常)。通过HostingEnvironment.QueueBackgroundWorkItem
调用SendMailAsync时可以使用它。