0

In the SmtpClient class, does SendAsyncCancel cancel the SendMailAsync method?

I see a few code examples on the www which imply it does.

However 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.

... which implies that it cancels SendAsync but not SendMailAsync.

Is there a way to cancel SendMailAsync? If not, why not?

If you want to cancel an asynchronous send (therefore use the old SendAsync instead of the newer SendMailAsync), what are any other disadvantages of using SendAsync instead of SendMailAsync?

ChrisW
  • 54,973
  • 13
  • 116
  • 224

1 Answers1

0

I tried to invoke SendMailAsync from a post-back handler of an ASP web page, and it threw an exception:

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()

From this I deduce two things:

  1. SendMailAsync is indeed implemented using SendAsync (you can see it on the call-stack of the exception). SendAsyncCancel therefore will presumably work for SendMailAsync too.
  2. You can't call SendMailAsync from an ASP unless you want to deal with the "Asynchronous operations are not allowed in this context" problem. That's discussed here and looks like it might be messy. Whereas I guess that calling SendAsync probably doesn't have this problem (because I'm using HttpClient.SendAsync and ContinueWith elsewhere, with a CountdownEvent.Wait at the end to wait for the operation to complete, without seeing this exception being thrown).

SendMailAsync can be used when it's invoked via HostingEnvironment.QueueBackgroundWorkItem.

Community
  • 1
  • 1
ChrisW
  • 54,973
  • 13
  • 116
  • 224