首页 > 解决方案 > 在这种情况下不允许异步操作

问题描述

我正在设置发送邮件的功能,但出现以下异常:

 "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",

这是功能:

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);
        }

标签: c#

解决方案


启动异步操作的页面必须将 Async 属性设置为 true,并且只能在 PreRenderComplete 事件之前的页面上启动异步操作。

您是否将Page.Async属性设置为true,并且您是否在PreRenderComplete事件之前启动了异步操作?

一般来说,你应该避免async void. 而不是async void你应该

  1. 确保您的应用程序面向 4.5(或更高版本)并已httpRuntime.targetFramework设置为 4.5(或更高版本)。
  2. 设置Page.Asynctrue
  3. 使用PageAsyncTaskwithRegisterAsyncTask来注册异步工作

推荐阅读