c# - 在这种情况下不允许异步操作
问题描述
我正在设置发送邮件的功能,但出现以下异常:
"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 属性设置为 true,并且只能在 PreRenderComplete 事件之前的页面上启动异步操作。
您是否将Page.Async
属性设置为true
,并且您是否在PreRenderComplete
事件之前启动了异步操作?
一般来说,你应该避免async void
. 而不是async void
,你应该:
- 确保您的应用程序面向 4.5(或更高版本)并已
httpRuntime.targetFramework
设置为 4.5(或更高版本)。 - 设置
Page.Async
为true
。 - 使用
PageAsyncTask
withRegisterAsyncTask
来注册异步工作。
推荐阅读
- node.js - nodejs+mongodb 在查询中使用文档的 _id 字段值访问 node.js 对象
- javascript - uWebSockets 并发会话
- email - PHP imap_open()、OpenSSL 和无密码
- asynchronous - 如何将 WsdlService 类型提供程序读入本地 F# 类并作为 C# 的非阻塞任务呈现
- typescript - typescript d.ts 文件中的枚举
- xml - 使用来自 xquery 的文档构造函数生成 XML 文件
- python - 为什么这些常量函数的性能不同?
- javascript - 如何指定/选择对象的特定属性
- python - Python - 如何将给定数字乘以给定字符串
- python - Python:需要索引的名称