【问题标题】:Asynchronous operations are not allowed in this context [duplicate]在这种情况下不允许异步操作[重复]
【发布时间】:2020-12-24 22:20:54
【问题描述】:

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

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

【问题讨论】:

  • async void 通常只能由事件处理程序使用。您是否尝试让该方法返回 async Task
  • 阅读错误信息。它字面意思告诉你该做什么。

标签: c#


【解决方案1】:

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

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

一般来说,you should avoid async void。而不是async voidyou should

  1. 确保您的应用面向 4.5(或更高版本)并将 httpRuntime.targetFramework 设置为 4.5(或更高版本)。
  2. Page.Async 设置为true
  3. Use PageAsyncTask with RegisterAsyncTask to register asynchronous work

【讨论】:

    猜你喜欢
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多