0

I added the following line (exactly as is, so you can try it too) to an asp.net WebApi action:

new SmtpClient { DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory}.SendMailAsync("a@test.com", "b@test.com", "s", "b");

and it caused the action to wait a few seconds, until throwing a 500 error of An asynchronous module or handler completed while an asynchronous operation was still pending. Clearly asp.net detected that there was an asynchronous task running.

Yet when I add

Task.Delay(10000);

the action completes immediately. Why does asp.net not detect here that there is an asynchronous task running?

wezten
  • 2,126
  • 3
  • 25
  • 48

1 Answers1

1

SmtpClient.SendAsync has the HostProtectionAttribute with the ExternalThreading flag on. Which indicates ASP.NET that new threads will be involved, so ASP.NET starts keeping count of these operations waiting for completion.

If you need to use async methods in WebForms you should use the RegisterAsyncTask method.

hardkoded
  • 18,915
  • 3
  • 52
  • 64
  • Thanks. Would do I do if I want to call SendMailAsync but I don't want the WebApi action to wait until the email is sent? I also don't want to tie up a thread by calling Task.Run. – wezten Jul 31 '17 at 08:13
  • 1
    You could take a look at posts like this one https://stackoverflow.com/questions/36335345/web-api-fire-and-forget Fire and forget are not a good recommendation in the Web. The WebServer could kill your process if he needs to. – hardkoded Jul 31 '17 at 12:39