-4

I'm setting up a function to send mail but I get the following exception:

 "message": "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.",
     "type": "System.InvalidOperationException",
     "source": "System.Web",

Here is the function:

public async void r102Implementation(ActivitiesModel instance)
        {
            var apiKey = Environment.GetEnvironmentVariable("API_KEY");
            var client = new SendGridClient(apiKey);
            var from = new EmailAddress("account@com.com", "Example User");
            var subject = "Sending with Twilio SendGrid is Fun";
            var to = new EmailAddress("account@com.com", "Example User");
            var plainTextContent = "and easy to do anywhere, even with C#";
            var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
            var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var response = await client.SendEmailAsync(msg).ConfigureAwait(false);
        }
yopipe
  • 1
  • 4

1 Answers1

0

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.

Have you set the Page.Async attribute to true, and are you starting the asynchronous operation before the PreRenderComplete event?

In general, you should avoid async void. Instead of async void, you should:

  1. Ensure your app is targeting 4.5 (or newer) and has httpRuntime.targetFramework set to 4.5 (or newer).
  2. Set Page.Async to true.
  3. Use PageAsyncTask with RegisterAsyncTask to register asynchronous work.
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810